1 //===-- SelectionDAG.cpp - Implement the SelectionDAG data structures -----===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This implements the SelectionDAG class. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/CodeGen/SelectionDAG.h" 15 #include "SDNodeDbgValue.h" 16 #include "llvm/ADT/APSInt.h" 17 #include "llvm/ADT/SetVector.h" 18 #include "llvm/ADT/SmallPtrSet.h" 19 #include "llvm/ADT/SmallSet.h" 20 #include "llvm/ADT/SmallVector.h" 21 #include "llvm/ADT/StringExtras.h" 22 #include "llvm/Analysis/ValueTracking.h" 23 #include "llvm/CodeGen/MachineBasicBlock.h" 24 #include "llvm/CodeGen/MachineConstantPool.h" 25 #include "llvm/CodeGen/MachineFrameInfo.h" 26 #include "llvm/CodeGen/MachineModuleInfo.h" 27 #include "llvm/CodeGen/SelectionDAGTargetInfo.h" 28 #include "llvm/IR/CallingConv.h" 29 #include "llvm/IR/Constants.h" 30 #include "llvm/IR/DataLayout.h" 31 #include "llvm/IR/DebugInfo.h" 32 #include "llvm/IR/DerivedTypes.h" 33 #include "llvm/IR/Function.h" 34 #include "llvm/IR/GlobalAlias.h" 35 #include "llvm/IR/GlobalVariable.h" 36 #include "llvm/IR/Intrinsics.h" 37 #include "llvm/Support/CommandLine.h" 38 #include "llvm/Support/Debug.h" 39 #include "llvm/Support/ErrorHandling.h" 40 #include "llvm/Support/ManagedStatic.h" 41 #include "llvm/Support/MathExtras.h" 42 #include "llvm/Support/Mutex.h" 43 #include "llvm/Support/raw_ostream.h" 44 #include "llvm/Target/TargetInstrInfo.h" 45 #include "llvm/Target/TargetIntrinsicInfo.h" 46 #include "llvm/Target/TargetLowering.h" 47 #include "llvm/Target/TargetMachine.h" 48 #include "llvm/Target/TargetOptions.h" 49 #include "llvm/Target/TargetRegisterInfo.h" 50 #include "llvm/Target/TargetSubtargetInfo.h" 51 #include <algorithm> 52 #include <cmath> 53 #include <utility> 54 55 using namespace llvm; 56 57 /// makeVTList - Return an instance of the SDVTList struct initialized with the 58 /// specified members. 59 static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) { 60 SDVTList Res = {VTs, NumVTs}; 61 return Res; 62 } 63 64 // Default null implementations of the callbacks. 65 void SelectionDAG::DAGUpdateListener::NodeDeleted(SDNode*, SDNode*) {} 66 void SelectionDAG::DAGUpdateListener::NodeUpdated(SDNode*) {} 67 68 //===----------------------------------------------------------------------===// 69 // ConstantFPSDNode Class 70 //===----------------------------------------------------------------------===// 71 72 /// isExactlyValue - We don't rely on operator== working on double values, as 73 /// it returns true for things that are clearly not equal, like -0.0 and 0.0. 74 /// As such, this method can be used to do an exact bit-for-bit comparison of 75 /// two floating point values. 76 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const { 77 return getValueAPF().bitwiseIsEqual(V); 78 } 79 80 bool ConstantFPSDNode::isValueValidForType(EVT VT, 81 const APFloat& Val) { 82 assert(VT.isFloatingPoint() && "Can only convert between FP types"); 83 84 // convert modifies in place, so make a copy. 85 APFloat Val2 = APFloat(Val); 86 bool losesInfo; 87 (void) Val2.convert(SelectionDAG::EVTToAPFloatSemantics(VT), 88 APFloat::rmNearestTiesToEven, 89 &losesInfo); 90 return !losesInfo; 91 } 92 93 //===----------------------------------------------------------------------===// 94 // ISD Namespace 95 //===----------------------------------------------------------------------===// 96 97 /// isBuildVectorAllOnes - Return true if the specified node is a 98 /// BUILD_VECTOR where all of the elements are ~0 or undef. 99 bool ISD::isBuildVectorAllOnes(const SDNode *N) { 100 // Look through a bit convert. 101 while (N->getOpcode() == ISD::BITCAST) 102 N = N->getOperand(0).getNode(); 103 104 if (N->getOpcode() != ISD::BUILD_VECTOR) return false; 105 106 unsigned i = 0, e = N->getNumOperands(); 107 108 // Skip over all of the undef values. 109 while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF) 110 ++i; 111 112 // Do not accept an all-undef vector. 113 if (i == e) return false; 114 115 // Do not accept build_vectors that aren't all constants or which have non-~0 116 // elements. We have to be a bit careful here, as the type of the constant 117 // may not be the same as the type of the vector elements due to type 118 // legalization (the elements are promoted to a legal type for the target and 119 // a vector of a type may be legal when the base element type is not). 120 // We only want to check enough bits to cover the vector elements, because 121 // we care if the resultant vector is all ones, not whether the individual 122 // constants are. 123 SDValue NotZero = N->getOperand(i); 124 unsigned EltSize = N->getValueType(0).getVectorElementType().getSizeInBits(); 125 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(NotZero)) { 126 if (CN->getAPIntValue().countTrailingOnes() < EltSize) 127 return false; 128 } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(NotZero)) { 129 if (CFPN->getValueAPF().bitcastToAPInt().countTrailingOnes() < EltSize) 130 return false; 131 } else 132 return false; 133 134 // Okay, we have at least one ~0 value, check to see if the rest match or are 135 // undefs. Even with the above element type twiddling, this should be OK, as 136 // the same type legalization should have applied to all the elements. 137 for (++i; i != e; ++i) 138 if (N->getOperand(i) != NotZero && 139 N->getOperand(i).getOpcode() != ISD::UNDEF) 140 return false; 141 return true; 142 } 143 144 145 /// isBuildVectorAllZeros - Return true if the specified node is a 146 /// BUILD_VECTOR where all of the elements are 0 or undef. 147 bool ISD::isBuildVectorAllZeros(const SDNode *N) { 148 // Look through a bit convert. 149 while (N->getOpcode() == ISD::BITCAST) 150 N = N->getOperand(0).getNode(); 151 152 if (N->getOpcode() != ISD::BUILD_VECTOR) return false; 153 154 bool IsAllUndef = true; 155 for (const SDValue &Op : N->op_values()) { 156 if (Op.getOpcode() == ISD::UNDEF) 157 continue; 158 IsAllUndef = false; 159 // Do not accept build_vectors that aren't all constants or which have non-0 160 // elements. We have to be a bit careful here, as the type of the constant 161 // may not be the same as the type of the vector elements due to type 162 // legalization (the elements are promoted to a legal type for the target 163 // and a vector of a type may be legal when the base element type is not). 164 // We only want to check enough bits to cover the vector elements, because 165 // we care if the resultant vector is all zeros, not whether the individual 166 // constants are. 167 unsigned EltSize = N->getValueType(0).getVectorElementType().getSizeInBits(); 168 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Op)) { 169 if (CN->getAPIntValue().countTrailingZeros() < EltSize) 170 return false; 171 } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(Op)) { 172 if (CFPN->getValueAPF().bitcastToAPInt().countTrailingZeros() < EltSize) 173 return false; 174 } else 175 return false; 176 } 177 178 // Do not accept an all-undef vector. 179 if (IsAllUndef) 180 return false; 181 return true; 182 } 183 184 /// \brief Return true if the specified node is a BUILD_VECTOR node of 185 /// all ConstantSDNode or undef. 186 bool ISD::isBuildVectorOfConstantSDNodes(const SDNode *N) { 187 if (N->getOpcode() != ISD::BUILD_VECTOR) 188 return false; 189 190 for (const SDValue &Op : N->op_values()) { 191 if (Op.getOpcode() == ISD::UNDEF) 192 continue; 193 if (!isa<ConstantSDNode>(Op)) 194 return false; 195 } 196 return true; 197 } 198 199 /// \brief Return true if the specified node is a BUILD_VECTOR node of 200 /// all ConstantFPSDNode or undef. 201 bool ISD::isBuildVectorOfConstantFPSDNodes(const SDNode *N) { 202 if (N->getOpcode() != ISD::BUILD_VECTOR) 203 return false; 204 205 for (const SDValue &Op : N->op_values()) { 206 if (Op.getOpcode() == ISD::UNDEF) 207 continue; 208 if (!isa<ConstantFPSDNode>(Op)) 209 return false; 210 } 211 return true; 212 } 213 214 /// allOperandsUndef - Return true if the node has at least one operand 215 /// and all operands of the specified node are ISD::UNDEF. 216 bool ISD::allOperandsUndef(const SDNode *N) { 217 // Return false if the node has no operands. 218 // This is "logically inconsistent" with the definition of "all" but 219 // is probably the desired behavior. 220 if (N->getNumOperands() == 0) 221 return false; 222 223 for (const SDValue &Op : N->op_values()) 224 if (Op.getOpcode() != ISD::UNDEF) 225 return false; 226 227 return true; 228 } 229 230 ISD::NodeType ISD::getExtForLoadExtType(bool IsFP, ISD::LoadExtType ExtType) { 231 switch (ExtType) { 232 case ISD::EXTLOAD: 233 return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND; 234 case ISD::SEXTLOAD: 235 return ISD::SIGN_EXTEND; 236 case ISD::ZEXTLOAD: 237 return ISD::ZERO_EXTEND; 238 default: 239 break; 240 } 241 242 llvm_unreachable("Invalid LoadExtType"); 243 } 244 245 /// getSetCCSwappedOperands - Return the operation corresponding to (Y op X) 246 /// when given the operation for (X op Y). 247 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) { 248 // To perform this operation, we just need to swap the L and G bits of the 249 // operation. 250 unsigned OldL = (Operation >> 2) & 1; 251 unsigned OldG = (Operation >> 1) & 1; 252 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits 253 (OldL << 1) | // New G bit 254 (OldG << 2)); // New L bit. 255 } 256 257 /// getSetCCInverse - Return the operation corresponding to !(X op Y), where 258 /// 'op' is a valid SetCC operation. 259 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, bool isInteger) { 260 unsigned Operation = Op; 261 if (isInteger) 262 Operation ^= 7; // Flip L, G, E bits, but not U. 263 else 264 Operation ^= 15; // Flip all of the condition bits. 265 266 if (Operation > ISD::SETTRUE2) 267 Operation &= ~8; // Don't let N and U bits get set. 268 269 return ISD::CondCode(Operation); 270 } 271 272 273 /// isSignedOp - For an integer comparison, return 1 if the comparison is a 274 /// signed operation and 2 if the result is an unsigned comparison. Return zero 275 /// if the operation does not depend on the sign of the input (setne and seteq). 276 static int isSignedOp(ISD::CondCode Opcode) { 277 switch (Opcode) { 278 default: llvm_unreachable("Illegal integer setcc operation!"); 279 case ISD::SETEQ: 280 case ISD::SETNE: return 0; 281 case ISD::SETLT: 282 case ISD::SETLE: 283 case ISD::SETGT: 284 case ISD::SETGE: return 1; 285 case ISD::SETULT: 286 case ISD::SETULE: 287 case ISD::SETUGT: 288 case ISD::SETUGE: return 2; 289 } 290 } 291 292 /// getSetCCOrOperation - Return the result of a logical OR between different 293 /// comparisons of identical values: ((X op1 Y) | (X op2 Y)). This function 294 /// returns SETCC_INVALID if it is not possible to represent the resultant 295 /// comparison. 296 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2, 297 bool isInteger) { 298 if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3) 299 // Cannot fold a signed integer setcc with an unsigned integer setcc. 300 return ISD::SETCC_INVALID; 301 302 unsigned Op = Op1 | Op2; // Combine all of the condition bits. 303 304 // If the N and U bits get set then the resultant comparison DOES suddenly 305 // care about orderedness, and is true when ordered. 306 if (Op > ISD::SETTRUE2) 307 Op &= ~16; // Clear the U bit if the N bit is set. 308 309 // Canonicalize illegal integer setcc's. 310 if (isInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT 311 Op = ISD::SETNE; 312 313 return ISD::CondCode(Op); 314 } 315 316 /// getSetCCAndOperation - Return the result of a logical AND between different 317 /// comparisons of identical values: ((X op1 Y) & (X op2 Y)). This 318 /// function returns zero if it is not possible to represent the resultant 319 /// comparison. 320 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2, 321 bool isInteger) { 322 if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3) 323 // Cannot fold a signed setcc with an unsigned setcc. 324 return ISD::SETCC_INVALID; 325 326 // Combine all of the condition bits. 327 ISD::CondCode Result = ISD::CondCode(Op1 & Op2); 328 329 // Canonicalize illegal integer setcc's. 330 if (isInteger) { 331 switch (Result) { 332 default: break; 333 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT 334 case ISD::SETOEQ: // SETEQ & SETU[LG]E 335 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE 336 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE 337 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE 338 } 339 } 340 341 return Result; 342 } 343 344 //===----------------------------------------------------------------------===// 345 // SDNode Profile Support 346 //===----------------------------------------------------------------------===// 347 348 /// AddNodeIDOpcode - Add the node opcode to the NodeID data. 349 /// 350 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) { 351 ID.AddInteger(OpC); 352 } 353 354 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them 355 /// solely with their pointer. 356 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) { 357 ID.AddPointer(VTList.VTs); 358 } 359 360 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data. 361 /// 362 static void AddNodeIDOperands(FoldingSetNodeID &ID, 363 ArrayRef<SDValue> Ops) { 364 for (auto& Op : Ops) { 365 ID.AddPointer(Op.getNode()); 366 ID.AddInteger(Op.getResNo()); 367 } 368 } 369 370 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data. 371 /// 372 static void AddNodeIDOperands(FoldingSetNodeID &ID, 373 ArrayRef<SDUse> Ops) { 374 for (auto& Op : Ops) { 375 ID.AddPointer(Op.getNode()); 376 ID.AddInteger(Op.getResNo()); 377 } 378 } 379 380 static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned short OpC, 381 SDVTList VTList, ArrayRef<SDValue> OpList) { 382 AddNodeIDOpcode(ID, OpC); 383 AddNodeIDValueTypes(ID, VTList); 384 AddNodeIDOperands(ID, OpList); 385 } 386 387 /// If this is an SDNode with special info, add this info to the NodeID data. 388 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) { 389 switch (N->getOpcode()) { 390 case ISD::TargetExternalSymbol: 391 case ISD::ExternalSymbol: 392 case ISD::MCSymbol: 393 llvm_unreachable("Should only be used on nodes with operands"); 394 default: break; // Normal nodes don't need extra info. 395 case ISD::TargetConstant: 396 case ISD::Constant: { 397 const ConstantSDNode *C = cast<ConstantSDNode>(N); 398 ID.AddPointer(C->getConstantIntValue()); 399 ID.AddBoolean(C->isOpaque()); 400 break; 401 } 402 case ISD::TargetConstantFP: 403 case ISD::ConstantFP: { 404 ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue()); 405 break; 406 } 407 case ISD::TargetGlobalAddress: 408 case ISD::GlobalAddress: 409 case ISD::TargetGlobalTLSAddress: 410 case ISD::GlobalTLSAddress: { 411 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N); 412 ID.AddPointer(GA->getGlobal()); 413 ID.AddInteger(GA->getOffset()); 414 ID.AddInteger(GA->getTargetFlags()); 415 ID.AddInteger(GA->getAddressSpace()); 416 break; 417 } 418 case ISD::BasicBlock: 419 ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock()); 420 break; 421 case ISD::Register: 422 ID.AddInteger(cast<RegisterSDNode>(N)->getReg()); 423 break; 424 case ISD::RegisterMask: 425 ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask()); 426 break; 427 case ISD::SRCVALUE: 428 ID.AddPointer(cast<SrcValueSDNode>(N)->getValue()); 429 break; 430 case ISD::FrameIndex: 431 case ISD::TargetFrameIndex: 432 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex()); 433 break; 434 case ISD::JumpTable: 435 case ISD::TargetJumpTable: 436 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex()); 437 ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags()); 438 break; 439 case ISD::ConstantPool: 440 case ISD::TargetConstantPool: { 441 const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N); 442 ID.AddInteger(CP->getAlignment()); 443 ID.AddInteger(CP->getOffset()); 444 if (CP->isMachineConstantPoolEntry()) 445 CP->getMachineCPVal()->addSelectionDAGCSEId(ID); 446 else 447 ID.AddPointer(CP->getConstVal()); 448 ID.AddInteger(CP->getTargetFlags()); 449 break; 450 } 451 case ISD::TargetIndex: { 452 const TargetIndexSDNode *TI = cast<TargetIndexSDNode>(N); 453 ID.AddInteger(TI->getIndex()); 454 ID.AddInteger(TI->getOffset()); 455 ID.AddInteger(TI->getTargetFlags()); 456 break; 457 } 458 case ISD::LOAD: { 459 const LoadSDNode *LD = cast<LoadSDNode>(N); 460 ID.AddInteger(LD->getMemoryVT().getRawBits()); 461 ID.AddInteger(LD->getRawSubclassData()); 462 ID.AddInteger(LD->getPointerInfo().getAddrSpace()); 463 break; 464 } 465 case ISD::STORE: { 466 const StoreSDNode *ST = cast<StoreSDNode>(N); 467 ID.AddInteger(ST->getMemoryVT().getRawBits()); 468 ID.AddInteger(ST->getRawSubclassData()); 469 ID.AddInteger(ST->getPointerInfo().getAddrSpace()); 470 break; 471 } 472 case ISD::ATOMIC_CMP_SWAP: 473 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 474 case ISD::ATOMIC_SWAP: 475 case ISD::ATOMIC_LOAD_ADD: 476 case ISD::ATOMIC_LOAD_SUB: 477 case ISD::ATOMIC_LOAD_AND: 478 case ISD::ATOMIC_LOAD_OR: 479 case ISD::ATOMIC_LOAD_XOR: 480 case ISD::ATOMIC_LOAD_NAND: 481 case ISD::ATOMIC_LOAD_MIN: 482 case ISD::ATOMIC_LOAD_MAX: 483 case ISD::ATOMIC_LOAD_UMIN: 484 case ISD::ATOMIC_LOAD_UMAX: 485 case ISD::ATOMIC_LOAD: 486 case ISD::ATOMIC_STORE: { 487 const AtomicSDNode *AT = cast<AtomicSDNode>(N); 488 ID.AddInteger(AT->getMemoryVT().getRawBits()); 489 ID.AddInteger(AT->getRawSubclassData()); 490 ID.AddInteger(AT->getPointerInfo().getAddrSpace()); 491 break; 492 } 493 case ISD::PREFETCH: { 494 const MemSDNode *PF = cast<MemSDNode>(N); 495 ID.AddInteger(PF->getPointerInfo().getAddrSpace()); 496 break; 497 } 498 case ISD::VECTOR_SHUFFLE: { 499 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 500 for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements(); 501 i != e; ++i) 502 ID.AddInteger(SVN->getMaskElt(i)); 503 break; 504 } 505 case ISD::TargetBlockAddress: 506 case ISD::BlockAddress: { 507 const BlockAddressSDNode *BA = cast<BlockAddressSDNode>(N); 508 ID.AddPointer(BA->getBlockAddress()); 509 ID.AddInteger(BA->getOffset()); 510 ID.AddInteger(BA->getTargetFlags()); 511 break; 512 } 513 } // end switch (N->getOpcode()) 514 515 // Target specific memory nodes could also have address spaces to check. 516 if (N->isTargetMemoryOpcode()) 517 ID.AddInteger(cast<MemSDNode>(N)->getPointerInfo().getAddrSpace()); 518 } 519 520 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID 521 /// data. 522 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) { 523 AddNodeIDOpcode(ID, N->getOpcode()); 524 // Add the return value info. 525 AddNodeIDValueTypes(ID, N->getVTList()); 526 // Add the operand info. 527 AddNodeIDOperands(ID, N->ops()); 528 529 // Handle SDNode leafs with special info. 530 AddNodeIDCustom(ID, N); 531 } 532 533 /// encodeMemSDNodeFlags - Generic routine for computing a value for use in 534 /// the CSE map that carries volatility, temporalness, indexing mode, and 535 /// extension/truncation information. 536 /// 537 static inline unsigned 538 encodeMemSDNodeFlags(int ConvType, ISD::MemIndexedMode AM, bool isVolatile, 539 bool isNonTemporal, bool isInvariant) { 540 assert((ConvType & 3) == ConvType && 541 "ConvType may not require more than 2 bits!"); 542 assert((AM & 7) == AM && 543 "AM may not require more than 3 bits!"); 544 return ConvType | 545 (AM << 2) | 546 (isVolatile << 5) | 547 (isNonTemporal << 6) | 548 (isInvariant << 7); 549 } 550 551 //===----------------------------------------------------------------------===// 552 // SelectionDAG Class 553 //===----------------------------------------------------------------------===// 554 555 /// doNotCSE - Return true if CSE should not be performed for this node. 556 static bool doNotCSE(SDNode *N) { 557 if (N->getValueType(0) == MVT::Glue) 558 return true; // Never CSE anything that produces a flag. 559 560 switch (N->getOpcode()) { 561 default: break; 562 case ISD::HANDLENODE: 563 case ISD::EH_LABEL: 564 return true; // Never CSE these nodes. 565 } 566 567 // Check that remaining values produced are not flags. 568 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i) 569 if (N->getValueType(i) == MVT::Glue) 570 return true; // Never CSE anything that produces a flag. 571 572 return false; 573 } 574 575 /// RemoveDeadNodes - This method deletes all unreachable nodes in the 576 /// SelectionDAG. 577 void SelectionDAG::RemoveDeadNodes() { 578 // Create a dummy node (which is not added to allnodes), that adds a reference 579 // to the root node, preventing it from being deleted. 580 HandleSDNode Dummy(getRoot()); 581 582 SmallVector<SDNode*, 128> DeadNodes; 583 584 // Add all obviously-dead nodes to the DeadNodes worklist. 585 for (SDNode &Node : allnodes()) 586 if (Node.use_empty()) 587 DeadNodes.push_back(&Node); 588 589 RemoveDeadNodes(DeadNodes); 590 591 // If the root changed (e.g. it was a dead load, update the root). 592 setRoot(Dummy.getValue()); 593 } 594 595 /// RemoveDeadNodes - This method deletes the unreachable nodes in the 596 /// given list, and any nodes that become unreachable as a result. 597 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes) { 598 599 // Process the worklist, deleting the nodes and adding their uses to the 600 // worklist. 601 while (!DeadNodes.empty()) { 602 SDNode *N = DeadNodes.pop_back_val(); 603 604 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 605 DUL->NodeDeleted(N, nullptr); 606 607 // Take the node out of the appropriate CSE map. 608 RemoveNodeFromCSEMaps(N); 609 610 // Next, brutally remove the operand list. This is safe to do, as there are 611 // no cycles in the graph. 612 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) { 613 SDUse &Use = *I++; 614 SDNode *Operand = Use.getNode(); 615 Use.set(SDValue()); 616 617 // Now that we removed this operand, see if there are no uses of it left. 618 if (Operand->use_empty()) 619 DeadNodes.push_back(Operand); 620 } 621 622 DeallocateNode(N); 623 } 624 } 625 626 void SelectionDAG::RemoveDeadNode(SDNode *N){ 627 SmallVector<SDNode*, 16> DeadNodes(1, N); 628 629 // Create a dummy node that adds a reference to the root node, preventing 630 // it from being deleted. (This matters if the root is an operand of the 631 // dead node.) 632 HandleSDNode Dummy(getRoot()); 633 634 RemoveDeadNodes(DeadNodes); 635 } 636 637 void SelectionDAG::DeleteNode(SDNode *N) { 638 // First take this out of the appropriate CSE map. 639 RemoveNodeFromCSEMaps(N); 640 641 // Finally, remove uses due to operands of this node, remove from the 642 // AllNodes list, and delete the node. 643 DeleteNodeNotInCSEMaps(N); 644 } 645 646 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) { 647 assert(N->getIterator() != AllNodes.begin() && 648 "Cannot delete the entry node!"); 649 assert(N->use_empty() && "Cannot delete a node that is not dead!"); 650 651 // Drop all of the operands and decrement used node's use counts. 652 N->DropOperands(); 653 654 DeallocateNode(N); 655 } 656 657 void SDDbgInfo::erase(const SDNode *Node) { 658 DbgValMapType::iterator I = DbgValMap.find(Node); 659 if (I == DbgValMap.end()) 660 return; 661 for (auto &Val: I->second) 662 Val->setIsInvalidated(); 663 DbgValMap.erase(I); 664 } 665 666 void SelectionDAG::DeallocateNode(SDNode *N) { 667 if (N->OperandsNeedDelete) 668 delete[] N->OperandList; 669 670 // Set the opcode to DELETED_NODE to help catch bugs when node 671 // memory is reallocated. 672 N->NodeType = ISD::DELETED_NODE; 673 674 NodeAllocator.Deallocate(AllNodes.remove(N)); 675 676 // If any of the SDDbgValue nodes refer to this SDNode, invalidate 677 // them and forget about that node. 678 DbgInfo->erase(N); 679 } 680 681 #ifndef NDEBUG 682 /// VerifySDNode - Sanity check the given SDNode. Aborts if it is invalid. 683 static void VerifySDNode(SDNode *N) { 684 switch (N->getOpcode()) { 685 default: 686 break; 687 case ISD::BUILD_PAIR: { 688 EVT VT = N->getValueType(0); 689 assert(N->getNumValues() == 1 && "Too many results!"); 690 assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) && 691 "Wrong return type!"); 692 assert(N->getNumOperands() == 2 && "Wrong number of operands!"); 693 assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() && 694 "Mismatched operand types!"); 695 assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() && 696 "Wrong operand type!"); 697 assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() && 698 "Wrong return type size"); 699 break; 700 } 701 case ISD::BUILD_VECTOR: { 702 assert(N->getNumValues() == 1 && "Too many results!"); 703 assert(N->getValueType(0).isVector() && "Wrong return type!"); 704 assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() && 705 "Wrong number of operands!"); 706 EVT EltVT = N->getValueType(0).getVectorElementType(); 707 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) { 708 assert((I->getValueType() == EltVT || 709 (EltVT.isInteger() && I->getValueType().isInteger() && 710 EltVT.bitsLE(I->getValueType()))) && 711 "Wrong operand type!"); 712 assert(I->getValueType() == N->getOperand(0).getValueType() && 713 "Operands must all have the same type"); 714 } 715 break; 716 } 717 } 718 } 719 #endif // NDEBUG 720 721 /// \brief Insert a newly allocated node into the DAG. 722 /// 723 /// Handles insertion into the all nodes list and CSE map, as well as 724 /// verification and other common operations when a new node is allocated. 725 void SelectionDAG::InsertNode(SDNode *N) { 726 AllNodes.push_back(N); 727 #ifndef NDEBUG 728 N->PersistentId = NextPersistentId++; 729 VerifySDNode(N); 730 #endif 731 } 732 733 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that 734 /// correspond to it. This is useful when we're about to delete or repurpose 735 /// the node. We don't want future request for structurally identical nodes 736 /// to return N anymore. 737 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) { 738 bool Erased = false; 739 switch (N->getOpcode()) { 740 case ISD::HANDLENODE: return false; // noop. 741 case ISD::CONDCODE: 742 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] && 743 "Cond code doesn't exist!"); 744 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr; 745 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr; 746 break; 747 case ISD::ExternalSymbol: 748 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol()); 749 break; 750 case ISD::TargetExternalSymbol: { 751 ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N); 752 Erased = TargetExternalSymbols.erase( 753 std::pair<std::string,unsigned char>(ESN->getSymbol(), 754 ESN->getTargetFlags())); 755 break; 756 } 757 case ISD::MCSymbol: { 758 auto *MCSN = cast<MCSymbolSDNode>(N); 759 Erased = MCSymbols.erase(MCSN->getMCSymbol()); 760 break; 761 } 762 case ISD::VALUETYPE: { 763 EVT VT = cast<VTSDNode>(N)->getVT(); 764 if (VT.isExtended()) { 765 Erased = ExtendedValueTypeNodes.erase(VT); 766 } else { 767 Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr; 768 ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr; 769 } 770 break; 771 } 772 default: 773 // Remove it from the CSE Map. 774 assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!"); 775 assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!"); 776 Erased = CSEMap.RemoveNode(N); 777 break; 778 } 779 #ifndef NDEBUG 780 // Verify that the node was actually in one of the CSE maps, unless it has a 781 // flag result (which cannot be CSE'd) or is one of the special cases that are 782 // not subject to CSE. 783 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue && 784 !N->isMachineOpcode() && !doNotCSE(N)) { 785 N->dump(this); 786 dbgs() << "\n"; 787 llvm_unreachable("Node is not in map!"); 788 } 789 #endif 790 return Erased; 791 } 792 793 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE 794 /// maps and modified in place. Add it back to the CSE maps, unless an identical 795 /// node already exists, in which case transfer all its users to the existing 796 /// node. This transfer can potentially trigger recursive merging. 797 /// 798 void 799 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) { 800 // For node types that aren't CSE'd, just act as if no identical node 801 // already exists. 802 if (!doNotCSE(N)) { 803 SDNode *Existing = CSEMap.GetOrInsertNode(N); 804 if (Existing != N) { 805 // If there was already an existing matching node, use ReplaceAllUsesWith 806 // to replace the dead one with the existing one. This can cause 807 // recursive merging of other unrelated nodes down the line. 808 ReplaceAllUsesWith(N, Existing); 809 810 // N is now dead. Inform the listeners and delete it. 811 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 812 DUL->NodeDeleted(N, Existing); 813 DeleteNodeNotInCSEMaps(N); 814 return; 815 } 816 } 817 818 // If the node doesn't already exist, we updated it. Inform listeners. 819 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 820 DUL->NodeUpdated(N); 821 } 822 823 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands 824 /// were replaced with those specified. If this node is never memoized, 825 /// return null, otherwise return a pointer to the slot it would take. If a 826 /// node already exists with these operands, the slot will be non-null. 827 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op, 828 void *&InsertPos) { 829 if (doNotCSE(N)) 830 return nullptr; 831 832 SDValue Ops[] = { Op }; 833 FoldingSetNodeID ID; 834 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops); 835 AddNodeIDCustom(ID, N); 836 SDNode *Node = FindNodeOrInsertPos(ID, N->getDebugLoc(), InsertPos); 837 if (Node) 838 if (const SDNodeFlags *Flags = N->getFlags()) 839 Node->intersectFlagsWith(Flags); 840 return Node; 841 } 842 843 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands 844 /// were replaced with those specified. If this node is never memoized, 845 /// return null, otherwise return a pointer to the slot it would take. If a 846 /// node already exists with these operands, the slot will be non-null. 847 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, 848 SDValue Op1, SDValue Op2, 849 void *&InsertPos) { 850 if (doNotCSE(N)) 851 return nullptr; 852 853 SDValue Ops[] = { Op1, Op2 }; 854 FoldingSetNodeID ID; 855 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops); 856 AddNodeIDCustom(ID, N); 857 SDNode *Node = FindNodeOrInsertPos(ID, N->getDebugLoc(), InsertPos); 858 if (Node) 859 if (const SDNodeFlags *Flags = N->getFlags()) 860 Node->intersectFlagsWith(Flags); 861 return Node; 862 } 863 864 865 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands 866 /// were replaced with those specified. If this node is never memoized, 867 /// return null, otherwise return a pointer to the slot it would take. If a 868 /// node already exists with these operands, the slot will be non-null. 869 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops, 870 void *&InsertPos) { 871 if (doNotCSE(N)) 872 return nullptr; 873 874 FoldingSetNodeID ID; 875 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops); 876 AddNodeIDCustom(ID, N); 877 SDNode *Node = FindNodeOrInsertPos(ID, N->getDebugLoc(), InsertPos); 878 if (Node) 879 if (const SDNodeFlags *Flags = N->getFlags()) 880 Node->intersectFlagsWith(Flags); 881 return Node; 882 } 883 884 /// getEVTAlignment - Compute the default alignment value for the 885 /// given type. 886 /// 887 unsigned SelectionDAG::getEVTAlignment(EVT VT) const { 888 Type *Ty = VT == MVT::iPTR ? 889 PointerType::get(Type::getInt8Ty(*getContext()), 0) : 890 VT.getTypeForEVT(*getContext()); 891 892 return getDataLayout().getABITypeAlignment(Ty); 893 } 894 895 // EntryNode could meaningfully have debug info if we can find it... 896 SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL) 897 : TM(tm), TSI(nullptr), TLI(nullptr), OptLevel(OL), 898 EntryNode(ISD::EntryToken, 0, DebugLoc(), getVTList(MVT::Other)), 899 Root(getEntryNode()), NewNodesMustHaveLegalTypes(false), 900 UpdateListeners(nullptr) { 901 InsertNode(&EntryNode); 902 DbgInfo = new SDDbgInfo(); 903 } 904 905 void SelectionDAG::init(MachineFunction &mf) { 906 MF = &mf; 907 TLI = getSubtarget().getTargetLowering(); 908 TSI = getSubtarget().getSelectionDAGInfo(); 909 Context = &mf.getFunction()->getContext(); 910 } 911 912 SelectionDAG::~SelectionDAG() { 913 assert(!UpdateListeners && "Dangling registered DAGUpdateListeners"); 914 allnodes_clear(); 915 delete DbgInfo; 916 } 917 918 void SelectionDAG::allnodes_clear() { 919 assert(&*AllNodes.begin() == &EntryNode); 920 AllNodes.remove(AllNodes.begin()); 921 while (!AllNodes.empty()) 922 DeallocateNode(&AllNodes.front()); 923 #ifndef NDEBUG 924 NextPersistentId = 0; 925 #endif 926 } 927 928 BinarySDNode *SelectionDAG::GetBinarySDNode(unsigned Opcode, SDLoc DL, 929 SDVTList VTs, SDValue N1, 930 SDValue N2, 931 const SDNodeFlags *Flags) { 932 if (isBinOpWithFlags(Opcode)) { 933 // If no flags were passed in, use a default flags object. 934 SDNodeFlags F; 935 if (Flags == nullptr) 936 Flags = &F; 937 938 BinaryWithFlagsSDNode *FN = new (NodeAllocator) BinaryWithFlagsSDNode( 939 Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs, N1, N2, *Flags); 940 941 return FN; 942 } 943 944 BinarySDNode *N = new (NodeAllocator) 945 BinarySDNode(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs, N1, N2); 946 return N; 947 } 948 949 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID, 950 void *&InsertPos) { 951 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos); 952 if (N) { 953 switch (N->getOpcode()) { 954 default: break; 955 case ISD::Constant: 956 case ISD::ConstantFP: 957 llvm_unreachable("Querying for Constant and ConstantFP nodes requires " 958 "debug location. Use another overload."); 959 } 960 } 961 return N; 962 } 963 964 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID, 965 DebugLoc DL, void *&InsertPos) { 966 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos); 967 if (N) { 968 switch (N->getOpcode()) { 969 default: break; // Process only regular (non-target) constant nodes. 970 case ISD::Constant: 971 case ISD::ConstantFP: 972 // Erase debug location from the node if the node is used at several 973 // different places to do not propagate one location to all uses as it 974 // leads to incorrect debug info. 975 if (N->getDebugLoc() != DL) 976 N->setDebugLoc(DebugLoc()); 977 break; 978 } 979 } 980 return N; 981 } 982 983 void SelectionDAG::clear() { 984 allnodes_clear(); 985 OperandAllocator.Reset(); 986 CSEMap.clear(); 987 988 ExtendedValueTypeNodes.clear(); 989 ExternalSymbols.clear(); 990 TargetExternalSymbols.clear(); 991 MCSymbols.clear(); 992 std::fill(CondCodeNodes.begin(), CondCodeNodes.end(), 993 static_cast<CondCodeSDNode*>(nullptr)); 994 std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(), 995 static_cast<SDNode*>(nullptr)); 996 997 EntryNode.UseList = nullptr; 998 InsertNode(&EntryNode); 999 Root = getEntryNode(); 1000 DbgInfo->clear(); 1001 } 1002 1003 SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, SDLoc DL, EVT VT) { 1004 return VT.bitsGT(Op.getValueType()) ? 1005 getNode(ISD::ANY_EXTEND, DL, VT, Op) : 1006 getNode(ISD::TRUNCATE, DL, VT, Op); 1007 } 1008 1009 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, SDLoc DL, EVT VT) { 1010 return VT.bitsGT(Op.getValueType()) ? 1011 getNode(ISD::SIGN_EXTEND, DL, VT, Op) : 1012 getNode(ISD::TRUNCATE, DL, VT, Op); 1013 } 1014 1015 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, SDLoc DL, EVT VT) { 1016 return VT.bitsGT(Op.getValueType()) ? 1017 getNode(ISD::ZERO_EXTEND, DL, VT, Op) : 1018 getNode(ISD::TRUNCATE, DL, VT, Op); 1019 } 1020 1021 SDValue SelectionDAG::getBoolExtOrTrunc(SDValue Op, SDLoc SL, EVT VT, 1022 EVT OpVT) { 1023 if (VT.bitsLE(Op.getValueType())) 1024 return getNode(ISD::TRUNCATE, SL, VT, Op); 1025 1026 TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT); 1027 return getNode(TLI->getExtendForContent(BType), SL, VT, Op); 1028 } 1029 1030 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, SDLoc DL, EVT VT) { 1031 assert(!VT.isVector() && 1032 "getZeroExtendInReg should use the vector element type instead of " 1033 "the vector type!"); 1034 if (Op.getValueType() == VT) return Op; 1035 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits(); 1036 APInt Imm = APInt::getLowBitsSet(BitWidth, 1037 VT.getSizeInBits()); 1038 return getNode(ISD::AND, DL, Op.getValueType(), Op, 1039 getConstant(Imm, DL, Op.getValueType())); 1040 } 1041 1042 SDValue SelectionDAG::getAnyExtendVectorInReg(SDValue Op, SDLoc DL, EVT VT) { 1043 assert(VT.isVector() && "This DAG node is restricted to vector types."); 1044 assert(VT.getSizeInBits() == Op.getValueType().getSizeInBits() && 1045 "The sizes of the input and result must match in order to perform the " 1046 "extend in-register."); 1047 assert(VT.getVectorNumElements() < Op.getValueType().getVectorNumElements() && 1048 "The destination vector type must have fewer lanes than the input."); 1049 return getNode(ISD::ANY_EXTEND_VECTOR_INREG, DL, VT, Op); 1050 } 1051 1052 SDValue SelectionDAG::getSignExtendVectorInReg(SDValue Op, SDLoc DL, EVT VT) { 1053 assert(VT.isVector() && "This DAG node is restricted to vector types."); 1054 assert(VT.getSizeInBits() == Op.getValueType().getSizeInBits() && 1055 "The sizes of the input and result must match in order to perform the " 1056 "extend in-register."); 1057 assert(VT.getVectorNumElements() < Op.getValueType().getVectorNumElements() && 1058 "The destination vector type must have fewer lanes than the input."); 1059 return getNode(ISD::SIGN_EXTEND_VECTOR_INREG, DL, VT, Op); 1060 } 1061 1062 SDValue SelectionDAG::getZeroExtendVectorInReg(SDValue Op, SDLoc DL, EVT VT) { 1063 assert(VT.isVector() && "This DAG node is restricted to vector types."); 1064 assert(VT.getSizeInBits() == Op.getValueType().getSizeInBits() && 1065 "The sizes of the input and result must match in order to perform the " 1066 "extend in-register."); 1067 assert(VT.getVectorNumElements() < Op.getValueType().getVectorNumElements() && 1068 "The destination vector type must have fewer lanes than the input."); 1069 return getNode(ISD::ZERO_EXTEND_VECTOR_INREG, DL, VT, Op); 1070 } 1071 1072 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1). 1073 /// 1074 SDValue SelectionDAG::getNOT(SDLoc DL, SDValue Val, EVT VT) { 1075 EVT EltVT = VT.getScalarType(); 1076 SDValue NegOne = 1077 getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), DL, VT); 1078 return getNode(ISD::XOR, DL, VT, Val, NegOne); 1079 } 1080 1081 SDValue SelectionDAG::getLogicalNOT(SDLoc DL, SDValue Val, EVT VT) { 1082 EVT EltVT = VT.getScalarType(); 1083 SDValue TrueValue; 1084 switch (TLI->getBooleanContents(VT)) { 1085 case TargetLowering::ZeroOrOneBooleanContent: 1086 case TargetLowering::UndefinedBooleanContent: 1087 TrueValue = getConstant(1, DL, VT); 1088 break; 1089 case TargetLowering::ZeroOrNegativeOneBooleanContent: 1090 TrueValue = getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), DL, 1091 VT); 1092 break; 1093 } 1094 return getNode(ISD::XOR, DL, VT, Val, TrueValue); 1095 } 1096 1097 SDValue SelectionDAG::getConstant(uint64_t Val, SDLoc DL, EVT VT, bool isT, 1098 bool isO) { 1099 EVT EltVT = VT.getScalarType(); 1100 assert((EltVT.getSizeInBits() >= 64 || 1101 (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) && 1102 "getConstant with a uint64_t value that doesn't fit in the type!"); 1103 return getConstant(APInt(EltVT.getSizeInBits(), Val), DL, VT, isT, isO); 1104 } 1105 1106 SDValue SelectionDAG::getConstant(const APInt &Val, SDLoc DL, EVT VT, bool isT, 1107 bool isO) { 1108 return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO); 1109 } 1110 1111 SDValue SelectionDAG::getConstant(const ConstantInt &Val, SDLoc DL, EVT VT, 1112 bool isT, bool isO) { 1113 assert(VT.isInteger() && "Cannot create FP integer constant!"); 1114 1115 EVT EltVT = VT.getScalarType(); 1116 const ConstantInt *Elt = &Val; 1117 1118 // In some cases the vector type is legal but the element type is illegal and 1119 // needs to be promoted, for example v8i8 on ARM. In this case, promote the 1120 // inserted value (the type does not need to match the vector element type). 1121 // Any extra bits introduced will be truncated away. 1122 if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) == 1123 TargetLowering::TypePromoteInteger) { 1124 EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT); 1125 APInt NewVal = Elt->getValue().zext(EltVT.getSizeInBits()); 1126 Elt = ConstantInt::get(*getContext(), NewVal); 1127 } 1128 // In other cases the element type is illegal and needs to be expanded, for 1129 // example v2i64 on MIPS32. In this case, find the nearest legal type, split 1130 // the value into n parts and use a vector type with n-times the elements. 1131 // Then bitcast to the type requested. 1132 // Legalizing constants too early makes the DAGCombiner's job harder so we 1133 // only legalize if the DAG tells us we must produce legal types. 1134 else if (NewNodesMustHaveLegalTypes && VT.isVector() && 1135 TLI->getTypeAction(*getContext(), EltVT) == 1136 TargetLowering::TypeExpandInteger) { 1137 APInt NewVal = Elt->getValue(); 1138 EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT); 1139 unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits(); 1140 unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits; 1141 EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts); 1142 1143 // Check the temporary vector is the correct size. If this fails then 1144 // getTypeToTransformTo() probably returned a type whose size (in bits) 1145 // isn't a power-of-2 factor of the requested type size. 1146 assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits()); 1147 1148 SmallVector<SDValue, 2> EltParts; 1149 for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i) { 1150 EltParts.push_back(getConstant(NewVal.lshr(i * ViaEltSizeInBits) 1151 .trunc(ViaEltSizeInBits), DL, 1152 ViaEltVT, isT, isO)); 1153 } 1154 1155 // EltParts is currently in little endian order. If we actually want 1156 // big-endian order then reverse it now. 1157 if (getDataLayout().isBigEndian()) 1158 std::reverse(EltParts.begin(), EltParts.end()); 1159 1160 // The elements must be reversed when the element order is different 1161 // to the endianness of the elements (because the BITCAST is itself a 1162 // vector shuffle in this situation). However, we do not need any code to 1163 // perform this reversal because getConstant() is producing a vector 1164 // splat. 1165 // This situation occurs in MIPS MSA. 1166 1167 SmallVector<SDValue, 8> Ops; 1168 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) 1169 Ops.insert(Ops.end(), EltParts.begin(), EltParts.end()); 1170 1171 SDValue Result = getNode(ISD::BITCAST, DL, VT, 1172 getNode(ISD::BUILD_VECTOR, DL, ViaVecVT, Ops)); 1173 return Result; 1174 } 1175 1176 assert(Elt->getBitWidth() == EltVT.getSizeInBits() && 1177 "APInt size does not match type size!"); 1178 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant; 1179 FoldingSetNodeID ID; 1180 AddNodeIDNode(ID, Opc, getVTList(EltVT), None); 1181 ID.AddPointer(Elt); 1182 ID.AddBoolean(isO); 1183 void *IP = nullptr; 1184 SDNode *N = nullptr; 1185 if ((N = FindNodeOrInsertPos(ID, DL.getDebugLoc(), IP))) 1186 if (!VT.isVector()) 1187 return SDValue(N, 0); 1188 1189 if (!N) { 1190 N = new (NodeAllocator) ConstantSDNode(isT, isO, Elt, DL.getDebugLoc(), 1191 EltVT); 1192 CSEMap.InsertNode(N, IP); 1193 InsertNode(N); 1194 } 1195 1196 SDValue Result(N, 0); 1197 if (VT.isVector()) { 1198 SmallVector<SDValue, 8> Ops; 1199 Ops.assign(VT.getVectorNumElements(), Result); 1200 Result = getNode(ISD::BUILD_VECTOR, DL, VT, Ops); 1201 } 1202 return Result; 1203 } 1204 1205 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, SDLoc DL, bool isTarget) { 1206 return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget); 1207 } 1208 1209 SDValue SelectionDAG::getConstantFP(const APFloat& V, SDLoc DL, EVT VT, 1210 bool isTarget) { 1211 return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget); 1212 } 1213 1214 SDValue SelectionDAG::getConstantFP(const ConstantFP& V, SDLoc DL, EVT VT, 1215 bool isTarget){ 1216 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!"); 1217 1218 EVT EltVT = VT.getScalarType(); 1219 1220 // Do the map lookup using the actual bit pattern for the floating point 1221 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and 1222 // we don't have issues with SNANs. 1223 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP; 1224 FoldingSetNodeID ID; 1225 AddNodeIDNode(ID, Opc, getVTList(EltVT), None); 1226 ID.AddPointer(&V); 1227 void *IP = nullptr; 1228 SDNode *N = nullptr; 1229 if ((N = FindNodeOrInsertPos(ID, DL.getDebugLoc(), IP))) 1230 if (!VT.isVector()) 1231 return SDValue(N, 0); 1232 1233 if (!N) { 1234 N = new (NodeAllocator) ConstantFPSDNode(isTarget, &V, DL.getDebugLoc(), 1235 EltVT); 1236 CSEMap.InsertNode(N, IP); 1237 InsertNode(N); 1238 } 1239 1240 SDValue Result(N, 0); 1241 if (VT.isVector()) { 1242 SmallVector<SDValue, 8> Ops; 1243 Ops.assign(VT.getVectorNumElements(), Result); 1244 Result = getNode(ISD::BUILD_VECTOR, DL, VT, Ops); 1245 } 1246 return Result; 1247 } 1248 1249 SDValue SelectionDAG::getConstantFP(double Val, SDLoc DL, EVT VT, 1250 bool isTarget) { 1251 EVT EltVT = VT.getScalarType(); 1252 if (EltVT == MVT::f32) 1253 return getConstantFP(APFloat((float)Val), DL, VT, isTarget); 1254 else if (EltVT == MVT::f64) 1255 return getConstantFP(APFloat(Val), DL, VT, isTarget); 1256 else if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 || 1257 EltVT == MVT::f16) { 1258 bool Ignored; 1259 APFloat APF = APFloat(Val); 1260 APF.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven, 1261 &Ignored); 1262 return getConstantFP(APF, DL, VT, isTarget); 1263 } else 1264 llvm_unreachable("Unsupported type in getConstantFP"); 1265 } 1266 1267 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, SDLoc DL, 1268 EVT VT, int64_t Offset, 1269 bool isTargetGA, 1270 unsigned char TargetFlags) { 1271 assert((TargetFlags == 0 || isTargetGA) && 1272 "Cannot set target flags on target-independent globals"); 1273 1274 // Truncate (with sign-extension) the offset value to the pointer size. 1275 unsigned BitWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType()); 1276 if (BitWidth < 64) 1277 Offset = SignExtend64(Offset, BitWidth); 1278 1279 unsigned Opc; 1280 if (GV->isThreadLocal()) 1281 Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress; 1282 else 1283 Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress; 1284 1285 FoldingSetNodeID ID; 1286 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1287 ID.AddPointer(GV); 1288 ID.AddInteger(Offset); 1289 ID.AddInteger(TargetFlags); 1290 ID.AddInteger(GV->getType()->getAddressSpace()); 1291 void *IP = nullptr; 1292 if (SDNode *E = FindNodeOrInsertPos(ID, DL.getDebugLoc(), IP)) 1293 return SDValue(E, 0); 1294 1295 SDNode *N = new (NodeAllocator) GlobalAddressSDNode(Opc, DL.getIROrder(), 1296 DL.getDebugLoc(), GV, VT, 1297 Offset, TargetFlags); 1298 CSEMap.InsertNode(N, IP); 1299 InsertNode(N); 1300 return SDValue(N, 0); 1301 } 1302 1303 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) { 1304 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex; 1305 FoldingSetNodeID ID; 1306 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1307 ID.AddInteger(FI); 1308 void *IP = nullptr; 1309 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1310 return SDValue(E, 0); 1311 1312 SDNode *N = new (NodeAllocator) FrameIndexSDNode(FI, VT, isTarget); 1313 CSEMap.InsertNode(N, IP); 1314 InsertNode(N); 1315 return SDValue(N, 0); 1316 } 1317 1318 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget, 1319 unsigned char TargetFlags) { 1320 assert((TargetFlags == 0 || isTarget) && 1321 "Cannot set target flags on target-independent jump tables"); 1322 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable; 1323 FoldingSetNodeID ID; 1324 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1325 ID.AddInteger(JTI); 1326 ID.AddInteger(TargetFlags); 1327 void *IP = nullptr; 1328 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1329 return SDValue(E, 0); 1330 1331 SDNode *N = new (NodeAllocator) JumpTableSDNode(JTI, VT, isTarget, 1332 TargetFlags); 1333 CSEMap.InsertNode(N, IP); 1334 InsertNode(N); 1335 return SDValue(N, 0); 1336 } 1337 1338 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT, 1339 unsigned Alignment, int Offset, 1340 bool isTarget, 1341 unsigned char TargetFlags) { 1342 assert((TargetFlags == 0 || isTarget) && 1343 "Cannot set target flags on target-independent globals"); 1344 if (Alignment == 0) 1345 Alignment = getDataLayout().getPrefTypeAlignment(C->getType()); 1346 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool; 1347 FoldingSetNodeID ID; 1348 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1349 ID.AddInteger(Alignment); 1350 ID.AddInteger(Offset); 1351 ID.AddPointer(C); 1352 ID.AddInteger(TargetFlags); 1353 void *IP = nullptr; 1354 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1355 return SDValue(E, 0); 1356 1357 SDNode *N = new (NodeAllocator) ConstantPoolSDNode(isTarget, C, VT, Offset, 1358 Alignment, TargetFlags); 1359 CSEMap.InsertNode(N, IP); 1360 InsertNode(N); 1361 return SDValue(N, 0); 1362 } 1363 1364 1365 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT, 1366 unsigned Alignment, int Offset, 1367 bool isTarget, 1368 unsigned char TargetFlags) { 1369 assert((TargetFlags == 0 || isTarget) && 1370 "Cannot set target flags on target-independent globals"); 1371 if (Alignment == 0) 1372 Alignment = getDataLayout().getPrefTypeAlignment(C->getType()); 1373 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool; 1374 FoldingSetNodeID ID; 1375 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1376 ID.AddInteger(Alignment); 1377 ID.AddInteger(Offset); 1378 C->addSelectionDAGCSEId(ID); 1379 ID.AddInteger(TargetFlags); 1380 void *IP = nullptr; 1381 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1382 return SDValue(E, 0); 1383 1384 SDNode *N = new (NodeAllocator) ConstantPoolSDNode(isTarget, C, VT, Offset, 1385 Alignment, TargetFlags); 1386 CSEMap.InsertNode(N, IP); 1387 InsertNode(N); 1388 return SDValue(N, 0); 1389 } 1390 1391 SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset, 1392 unsigned char TargetFlags) { 1393 FoldingSetNodeID ID; 1394 AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), None); 1395 ID.AddInteger(Index); 1396 ID.AddInteger(Offset); 1397 ID.AddInteger(TargetFlags); 1398 void *IP = nullptr; 1399 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1400 return SDValue(E, 0); 1401 1402 SDNode *N = 1403 new (NodeAllocator) TargetIndexSDNode(Index, VT, Offset, TargetFlags); 1404 CSEMap.InsertNode(N, IP); 1405 InsertNode(N); 1406 return SDValue(N, 0); 1407 } 1408 1409 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) { 1410 FoldingSetNodeID ID; 1411 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), None); 1412 ID.AddPointer(MBB); 1413 void *IP = nullptr; 1414 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1415 return SDValue(E, 0); 1416 1417 SDNode *N = new (NodeAllocator) BasicBlockSDNode(MBB); 1418 CSEMap.InsertNode(N, IP); 1419 InsertNode(N); 1420 return SDValue(N, 0); 1421 } 1422 1423 SDValue SelectionDAG::getValueType(EVT VT) { 1424 if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >= 1425 ValueTypeNodes.size()) 1426 ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1); 1427 1428 SDNode *&N = VT.isExtended() ? 1429 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy]; 1430 1431 if (N) return SDValue(N, 0); 1432 N = new (NodeAllocator) VTSDNode(VT); 1433 InsertNode(N); 1434 return SDValue(N, 0); 1435 } 1436 1437 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) { 1438 SDNode *&N = ExternalSymbols[Sym]; 1439 if (N) return SDValue(N, 0); 1440 N = new (NodeAllocator) ExternalSymbolSDNode(false, Sym, 0, VT); 1441 InsertNode(N); 1442 return SDValue(N, 0); 1443 } 1444 1445 SDValue SelectionDAG::getMCSymbol(MCSymbol *Sym, EVT VT) { 1446 SDNode *&N = MCSymbols[Sym]; 1447 if (N) 1448 return SDValue(N, 0); 1449 N = new (NodeAllocator) MCSymbolSDNode(Sym, VT); 1450 InsertNode(N); 1451 return SDValue(N, 0); 1452 } 1453 1454 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT, 1455 unsigned char TargetFlags) { 1456 SDNode *&N = 1457 TargetExternalSymbols[std::pair<std::string,unsigned char>(Sym, 1458 TargetFlags)]; 1459 if (N) return SDValue(N, 0); 1460 N = new (NodeAllocator) ExternalSymbolSDNode(true, Sym, TargetFlags, VT); 1461 InsertNode(N); 1462 return SDValue(N, 0); 1463 } 1464 1465 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) { 1466 if ((unsigned)Cond >= CondCodeNodes.size()) 1467 CondCodeNodes.resize(Cond+1); 1468 1469 if (!CondCodeNodes[Cond]) { 1470 CondCodeSDNode *N = new (NodeAllocator) CondCodeSDNode(Cond); 1471 CondCodeNodes[Cond] = N; 1472 InsertNode(N); 1473 } 1474 1475 return SDValue(CondCodeNodes[Cond], 0); 1476 } 1477 1478 // commuteShuffle - swaps the values of N1 and N2, and swaps all indices in 1479 // the shuffle mask M that point at N1 to point at N2, and indices that point 1480 // N2 to point at N1. 1481 static void commuteShuffle(SDValue &N1, SDValue &N2, SmallVectorImpl<int> &M) { 1482 std::swap(N1, N2); 1483 ShuffleVectorSDNode::commuteMask(M); 1484 } 1485 1486 SDValue SelectionDAG::getVectorShuffle(EVT VT, SDLoc dl, SDValue N1, 1487 SDValue N2, const int *Mask) { 1488 assert(VT == N1.getValueType() && VT == N2.getValueType() && 1489 "Invalid VECTOR_SHUFFLE"); 1490 1491 // Canonicalize shuffle undef, undef -> undef 1492 if (N1.getOpcode() == ISD::UNDEF && N2.getOpcode() == ISD::UNDEF) 1493 return getUNDEF(VT); 1494 1495 // Validate that all indices in Mask are within the range of the elements 1496 // input to the shuffle. 1497 unsigned NElts = VT.getVectorNumElements(); 1498 SmallVector<int, 8> MaskVec; 1499 for (unsigned i = 0; i != NElts; ++i) { 1500 assert(Mask[i] < (int)(NElts * 2) && "Index out of range"); 1501 MaskVec.push_back(Mask[i]); 1502 } 1503 1504 // Canonicalize shuffle v, v -> v, undef 1505 if (N1 == N2) { 1506 N2 = getUNDEF(VT); 1507 for (unsigned i = 0; i != NElts; ++i) 1508 if (MaskVec[i] >= (int)NElts) MaskVec[i] -= NElts; 1509 } 1510 1511 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask. 1512 if (N1.getOpcode() == ISD::UNDEF) 1513 commuteShuffle(N1, N2, MaskVec); 1514 1515 // If shuffling a splat, try to blend the splat instead. We do this here so 1516 // that even when this arises during lowering we don't have to re-handle it. 1517 auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) { 1518 BitVector UndefElements; 1519 SDValue Splat = BV->getSplatValue(&UndefElements); 1520 if (!Splat) 1521 return; 1522 1523 for (int i = 0; i < (int)NElts; ++i) { 1524 if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + (int)NElts)) 1525 continue; 1526 1527 // If this input comes from undef, mark it as such. 1528 if (UndefElements[MaskVec[i] - Offset]) { 1529 MaskVec[i] = -1; 1530 continue; 1531 } 1532 1533 // If we can blend a non-undef lane, use that instead. 1534 if (!UndefElements[i]) 1535 MaskVec[i] = i + Offset; 1536 } 1537 }; 1538 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1)) 1539 BlendSplat(N1BV, 0); 1540 if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2)) 1541 BlendSplat(N2BV, NElts); 1542 1543 // Canonicalize all index into lhs, -> shuffle lhs, undef 1544 // Canonicalize all index into rhs, -> shuffle rhs, undef 1545 bool AllLHS = true, AllRHS = true; 1546 bool N2Undef = N2.getOpcode() == ISD::UNDEF; 1547 for (unsigned i = 0; i != NElts; ++i) { 1548 if (MaskVec[i] >= (int)NElts) { 1549 if (N2Undef) 1550 MaskVec[i] = -1; 1551 else 1552 AllLHS = false; 1553 } else if (MaskVec[i] >= 0) { 1554 AllRHS = false; 1555 } 1556 } 1557 if (AllLHS && AllRHS) 1558 return getUNDEF(VT); 1559 if (AllLHS && !N2Undef) 1560 N2 = getUNDEF(VT); 1561 if (AllRHS) { 1562 N1 = getUNDEF(VT); 1563 commuteShuffle(N1, N2, MaskVec); 1564 } 1565 // Reset our undef status after accounting for the mask. 1566 N2Undef = N2.getOpcode() == ISD::UNDEF; 1567 // Re-check whether both sides ended up undef. 1568 if (N1.getOpcode() == ISD::UNDEF && N2Undef) 1569 return getUNDEF(VT); 1570 1571 // If Identity shuffle return that node. 1572 bool Identity = true, AllSame = true; 1573 for (unsigned i = 0; i != NElts; ++i) { 1574 if (MaskVec[i] >= 0 && MaskVec[i] != (int)i) Identity = false; 1575 if (MaskVec[i] != MaskVec[0]) AllSame = false; 1576 } 1577 if (Identity && NElts) 1578 return N1; 1579 1580 // Shuffling a constant splat doesn't change the result. 1581 if (N2Undef) { 1582 SDValue V = N1; 1583 1584 // Look through any bitcasts. We check that these don't change the number 1585 // (and size) of elements and just changes their types. 1586 while (V.getOpcode() == ISD::BITCAST) 1587 V = V->getOperand(0); 1588 1589 // A splat should always show up as a build vector node. 1590 if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) { 1591 BitVector UndefElements; 1592 SDValue Splat = BV->getSplatValue(&UndefElements); 1593 // If this is a splat of an undef, shuffling it is also undef. 1594 if (Splat && Splat.getOpcode() == ISD::UNDEF) 1595 return getUNDEF(VT); 1596 1597 bool SameNumElts = 1598 V.getValueType().getVectorNumElements() == VT.getVectorNumElements(); 1599 1600 // We only have a splat which can skip shuffles if there is a splatted 1601 // value and no undef lanes rearranged by the shuffle. 1602 if (Splat && UndefElements.none()) { 1603 // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the 1604 // number of elements match or the value splatted is a zero constant. 1605 if (SameNumElts) 1606 return N1; 1607 if (auto *C = dyn_cast<ConstantSDNode>(Splat)) 1608 if (C->isNullValue()) 1609 return N1; 1610 } 1611 1612 // If the shuffle itself creates a splat, build the vector directly. 1613 if (AllSame && SameNumElts) { 1614 const SDValue &Splatted = BV->getOperand(MaskVec[0]); 1615 SmallVector<SDValue, 8> Ops(NElts, Splatted); 1616 1617 EVT BuildVT = BV->getValueType(0); 1618 SDValue NewBV = getNode(ISD::BUILD_VECTOR, dl, BuildVT, Ops); 1619 1620 // We may have jumped through bitcasts, so the type of the 1621 // BUILD_VECTOR may not match the type of the shuffle. 1622 if (BuildVT != VT) 1623 NewBV = getNode(ISD::BITCAST, dl, VT, NewBV); 1624 return NewBV; 1625 } 1626 } 1627 } 1628 1629 FoldingSetNodeID ID; 1630 SDValue Ops[2] = { N1, N2 }; 1631 AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops); 1632 for (unsigned i = 0; i != NElts; ++i) 1633 ID.AddInteger(MaskVec[i]); 1634 1635 void* IP = nullptr; 1636 if (SDNode *E = FindNodeOrInsertPos(ID, dl.getDebugLoc(), IP)) 1637 return SDValue(E, 0); 1638 1639 // Allocate the mask array for the node out of the BumpPtrAllocator, since 1640 // SDNode doesn't have access to it. This memory will be "leaked" when 1641 // the node is deallocated, but recovered when the NodeAllocator is released. 1642 int *MaskAlloc = OperandAllocator.Allocate<int>(NElts); 1643 memcpy(MaskAlloc, &MaskVec[0], NElts * sizeof(int)); 1644 1645 ShuffleVectorSDNode *N = 1646 new (NodeAllocator) ShuffleVectorSDNode(VT, dl.getIROrder(), 1647 dl.getDebugLoc(), N1, N2, 1648 MaskAlloc); 1649 CSEMap.InsertNode(N, IP); 1650 InsertNode(N); 1651 return SDValue(N, 0); 1652 } 1653 1654 SDValue SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode &SV) { 1655 MVT VT = SV.getSimpleValueType(0); 1656 SmallVector<int, 8> MaskVec(SV.getMask().begin(), SV.getMask().end()); 1657 ShuffleVectorSDNode::commuteMask(MaskVec); 1658 1659 SDValue Op0 = SV.getOperand(0); 1660 SDValue Op1 = SV.getOperand(1); 1661 return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, &MaskVec[0]); 1662 } 1663 1664 SDValue SelectionDAG::getConvertRndSat(EVT VT, SDLoc dl, 1665 SDValue Val, SDValue DTy, 1666 SDValue STy, SDValue Rnd, SDValue Sat, 1667 ISD::CvtCode Code) { 1668 // If the src and dest types are the same and the conversion is between 1669 // integer types of the same sign or two floats, no conversion is necessary. 1670 if (DTy == STy && 1671 (Code == ISD::CVT_UU || Code == ISD::CVT_SS || Code == ISD::CVT_FF)) 1672 return Val; 1673 1674 FoldingSetNodeID ID; 1675 SDValue Ops[] = { Val, DTy, STy, Rnd, Sat }; 1676 AddNodeIDNode(ID, ISD::CONVERT_RNDSAT, getVTList(VT), Ops); 1677 void* IP = nullptr; 1678 if (SDNode *E = FindNodeOrInsertPos(ID, dl.getDebugLoc(), IP)) 1679 return SDValue(E, 0); 1680 1681 CvtRndSatSDNode *N = new (NodeAllocator) CvtRndSatSDNode(VT, dl.getIROrder(), 1682 dl.getDebugLoc(), 1683 Ops, Code); 1684 CSEMap.InsertNode(N, IP); 1685 InsertNode(N); 1686 return SDValue(N, 0); 1687 } 1688 1689 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) { 1690 FoldingSetNodeID ID; 1691 AddNodeIDNode(ID, ISD::Register, getVTList(VT), None); 1692 ID.AddInteger(RegNo); 1693 void *IP = nullptr; 1694 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1695 return SDValue(E, 0); 1696 1697 SDNode *N = new (NodeAllocator) RegisterSDNode(RegNo, VT); 1698 CSEMap.InsertNode(N, IP); 1699 InsertNode(N); 1700 return SDValue(N, 0); 1701 } 1702 1703 SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) { 1704 FoldingSetNodeID ID; 1705 AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), None); 1706 ID.AddPointer(RegMask); 1707 void *IP = nullptr; 1708 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1709 return SDValue(E, 0); 1710 1711 SDNode *N = new (NodeAllocator) RegisterMaskSDNode(RegMask); 1712 CSEMap.InsertNode(N, IP); 1713 InsertNode(N); 1714 return SDValue(N, 0); 1715 } 1716 1717 SDValue SelectionDAG::getEHLabel(SDLoc dl, SDValue Root, MCSymbol *Label) { 1718 FoldingSetNodeID ID; 1719 SDValue Ops[] = { Root }; 1720 AddNodeIDNode(ID, ISD::EH_LABEL, getVTList(MVT::Other), Ops); 1721 ID.AddPointer(Label); 1722 void *IP = nullptr; 1723 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1724 return SDValue(E, 0); 1725 1726 SDNode *N = new (NodeAllocator) EHLabelSDNode(dl.getIROrder(), 1727 dl.getDebugLoc(), Root, Label); 1728 CSEMap.InsertNode(N, IP); 1729 InsertNode(N); 1730 return SDValue(N, 0); 1731 } 1732 1733 1734 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT, 1735 int64_t Offset, 1736 bool isTarget, 1737 unsigned char TargetFlags) { 1738 unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress; 1739 1740 FoldingSetNodeID ID; 1741 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1742 ID.AddPointer(BA); 1743 ID.AddInteger(Offset); 1744 ID.AddInteger(TargetFlags); 1745 void *IP = nullptr; 1746 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1747 return SDValue(E, 0); 1748 1749 SDNode *N = new (NodeAllocator) BlockAddressSDNode(Opc, VT, BA, Offset, 1750 TargetFlags); 1751 CSEMap.InsertNode(N, IP); 1752 InsertNode(N); 1753 return SDValue(N, 0); 1754 } 1755 1756 SDValue SelectionDAG::getSrcValue(const Value *V) { 1757 assert((!V || V->getType()->isPointerTy()) && 1758 "SrcValue is not a pointer?"); 1759 1760 FoldingSetNodeID ID; 1761 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), None); 1762 ID.AddPointer(V); 1763 1764 void *IP = nullptr; 1765 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1766 return SDValue(E, 0); 1767 1768 SDNode *N = new (NodeAllocator) SrcValueSDNode(V); 1769 CSEMap.InsertNode(N, IP); 1770 InsertNode(N); 1771 return SDValue(N, 0); 1772 } 1773 1774 /// getMDNode - Return an MDNodeSDNode which holds an MDNode. 1775 SDValue SelectionDAG::getMDNode(const MDNode *MD) { 1776 FoldingSetNodeID ID; 1777 AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), None); 1778 ID.AddPointer(MD); 1779 1780 void *IP = nullptr; 1781 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1782 return SDValue(E, 0); 1783 1784 SDNode *N = new (NodeAllocator) MDNodeSDNode(MD); 1785 CSEMap.InsertNode(N, IP); 1786 InsertNode(N); 1787 return SDValue(N, 0); 1788 } 1789 1790 SDValue SelectionDAG::getBitcast(EVT VT, SDValue V) { 1791 if (VT == V.getValueType()) 1792 return V; 1793 1794 return getNode(ISD::BITCAST, SDLoc(V), VT, V); 1795 } 1796 1797 /// getAddrSpaceCast - Return an AddrSpaceCastSDNode. 1798 SDValue SelectionDAG::getAddrSpaceCast(SDLoc dl, EVT VT, SDValue Ptr, 1799 unsigned SrcAS, unsigned DestAS) { 1800 SDValue Ops[] = {Ptr}; 1801 FoldingSetNodeID ID; 1802 AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops); 1803 ID.AddInteger(SrcAS); 1804 ID.AddInteger(DestAS); 1805 1806 void *IP = nullptr; 1807 if (SDNode *E = FindNodeOrInsertPos(ID, dl.getDebugLoc(), IP)) 1808 return SDValue(E, 0); 1809 1810 SDNode *N = new (NodeAllocator) AddrSpaceCastSDNode(dl.getIROrder(), 1811 dl.getDebugLoc(), 1812 VT, Ptr, SrcAS, DestAS); 1813 CSEMap.InsertNode(N, IP); 1814 InsertNode(N); 1815 return SDValue(N, 0); 1816 } 1817 1818 /// getShiftAmountOperand - Return the specified value casted to 1819 /// the target's desired shift amount type. 1820 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) { 1821 EVT OpTy = Op.getValueType(); 1822 EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout()); 1823 if (OpTy == ShTy || OpTy.isVector()) return Op; 1824 1825 return getZExtOrTrunc(Op, SDLoc(Op), ShTy); 1826 } 1827 1828 SDValue SelectionDAG::expandVAArg(SDNode *Node) { 1829 SDLoc dl(Node); 1830 const TargetLowering &TLI = getTargetLoweringInfo(); 1831 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 1832 EVT VT = Node->getValueType(0); 1833 SDValue Tmp1 = Node->getOperand(0); 1834 SDValue Tmp2 = Node->getOperand(1); 1835 unsigned Align = Node->getConstantOperandVal(3); 1836 1837 SDValue VAListLoad = 1838 getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1, Tmp2, 1839 MachinePointerInfo(V), false, false, false, 0); 1840 SDValue VAList = VAListLoad; 1841 1842 if (Align > TLI.getMinStackArgumentAlignment()) { 1843 assert(((Align & (Align-1)) == 0) && "Expected Align to be a power of 2"); 1844 1845 VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList, 1846 getConstant(Align - 1, dl, VAList.getValueType())); 1847 1848 VAList = getNode(ISD::AND, dl, VAList.getValueType(), VAList, 1849 getConstant(-(int64_t)Align, dl, VAList.getValueType())); 1850 } 1851 1852 // Increment the pointer, VAList, to the next vaarg 1853 Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList, 1854 getConstant(getDataLayout().getTypeAllocSize( 1855 VT.getTypeForEVT(*getContext())), 1856 dl, VAList.getValueType())); 1857 // Store the incremented VAList to the legalized pointer 1858 Tmp1 = getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, 1859 MachinePointerInfo(V), false, false, 0); 1860 // Load the actual argument out of the pointer VAList 1861 return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo(), 1862 false, false, false, 0); 1863 } 1864 1865 SDValue SelectionDAG::expandVACopy(SDNode *Node) { 1866 SDLoc dl(Node); 1867 const TargetLowering &TLI = getTargetLoweringInfo(); 1868 // This defaults to loading a pointer from the input and storing it to the 1869 // output, returning the chain. 1870 const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue(); 1871 const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue(); 1872 SDValue Tmp1 = getLoad(TLI.getPointerTy(getDataLayout()), dl, 1873 Node->getOperand(0), Node->getOperand(2), 1874 MachinePointerInfo(VS), false, false, false, 0); 1875 return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1), 1876 MachinePointerInfo(VD), false, false, 0); 1877 } 1878 1879 /// CreateStackTemporary - Create a stack temporary, suitable for holding the 1880 /// specified value type. 1881 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) { 1882 MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo(); 1883 unsigned ByteSize = VT.getStoreSize(); 1884 Type *Ty = VT.getTypeForEVT(*getContext()); 1885 unsigned StackAlign = 1886 std::max((unsigned)getDataLayout().getPrefTypeAlignment(Ty), minAlign); 1887 1888 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false); 1889 return getFrameIndex(FrameIdx, TLI->getPointerTy(getDataLayout())); 1890 } 1891 1892 /// CreateStackTemporary - Create a stack temporary suitable for holding 1893 /// either of the specified value types. 1894 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) { 1895 unsigned Bytes = std::max(VT1.getStoreSize(), VT2.getStoreSize()); 1896 Type *Ty1 = VT1.getTypeForEVT(*getContext()); 1897 Type *Ty2 = VT2.getTypeForEVT(*getContext()); 1898 const DataLayout &DL = getDataLayout(); 1899 unsigned Align = 1900 std::max(DL.getPrefTypeAlignment(Ty1), DL.getPrefTypeAlignment(Ty2)); 1901 1902 MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo(); 1903 int FrameIdx = FrameInfo->CreateStackObject(Bytes, Align, false); 1904 return getFrameIndex(FrameIdx, TLI->getPointerTy(getDataLayout())); 1905 } 1906 1907 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, 1908 SDValue N2, ISD::CondCode Cond, SDLoc dl) { 1909 // These setcc operations always fold. 1910 switch (Cond) { 1911 default: break; 1912 case ISD::SETFALSE: 1913 case ISD::SETFALSE2: return getConstant(0, dl, VT); 1914 case ISD::SETTRUE: 1915 case ISD::SETTRUE2: { 1916 TargetLowering::BooleanContent Cnt = 1917 TLI->getBooleanContents(N1->getValueType(0)); 1918 return getConstant( 1919 Cnt == TargetLowering::ZeroOrNegativeOneBooleanContent ? -1ULL : 1, dl, 1920 VT); 1921 } 1922 1923 case ISD::SETOEQ: 1924 case ISD::SETOGT: 1925 case ISD::SETOGE: 1926 case ISD::SETOLT: 1927 case ISD::SETOLE: 1928 case ISD::SETONE: 1929 case ISD::SETO: 1930 case ISD::SETUO: 1931 case ISD::SETUEQ: 1932 case ISD::SETUNE: 1933 assert(!N1.getValueType().isInteger() && "Illegal setcc for integer!"); 1934 break; 1935 } 1936 1937 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2)) { 1938 const APInt &C2 = N2C->getAPIntValue(); 1939 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) { 1940 const APInt &C1 = N1C->getAPIntValue(); 1941 1942 switch (Cond) { 1943 default: llvm_unreachable("Unknown integer setcc!"); 1944 case ISD::SETEQ: return getConstant(C1 == C2, dl, VT); 1945 case ISD::SETNE: return getConstant(C1 != C2, dl, VT); 1946 case ISD::SETULT: return getConstant(C1.ult(C2), dl, VT); 1947 case ISD::SETUGT: return getConstant(C1.ugt(C2), dl, VT); 1948 case ISD::SETULE: return getConstant(C1.ule(C2), dl, VT); 1949 case ISD::SETUGE: return getConstant(C1.uge(C2), dl, VT); 1950 case ISD::SETLT: return getConstant(C1.slt(C2), dl, VT); 1951 case ISD::SETGT: return getConstant(C1.sgt(C2), dl, VT); 1952 case ISD::SETLE: return getConstant(C1.sle(C2), dl, VT); 1953 case ISD::SETGE: return getConstant(C1.sge(C2), dl, VT); 1954 } 1955 } 1956 } 1957 if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1)) { 1958 if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2)) { 1959 APFloat::cmpResult R = N1C->getValueAPF().compare(N2C->getValueAPF()); 1960 switch (Cond) { 1961 default: break; 1962 case ISD::SETEQ: if (R==APFloat::cmpUnordered) 1963 return getUNDEF(VT); 1964 // fall through 1965 case ISD::SETOEQ: return getConstant(R==APFloat::cmpEqual, dl, VT); 1966 case ISD::SETNE: if (R==APFloat::cmpUnordered) 1967 return getUNDEF(VT); 1968 // fall through 1969 case ISD::SETONE: return getConstant(R==APFloat::cmpGreaterThan || 1970 R==APFloat::cmpLessThan, dl, VT); 1971 case ISD::SETLT: if (R==APFloat::cmpUnordered) 1972 return getUNDEF(VT); 1973 // fall through 1974 case ISD::SETOLT: return getConstant(R==APFloat::cmpLessThan, dl, VT); 1975 case ISD::SETGT: if (R==APFloat::cmpUnordered) 1976 return getUNDEF(VT); 1977 // fall through 1978 case ISD::SETOGT: return getConstant(R==APFloat::cmpGreaterThan, dl, VT); 1979 case ISD::SETLE: if (R==APFloat::cmpUnordered) 1980 return getUNDEF(VT); 1981 // fall through 1982 case ISD::SETOLE: return getConstant(R==APFloat::cmpLessThan || 1983 R==APFloat::cmpEqual, dl, VT); 1984 case ISD::SETGE: if (R==APFloat::cmpUnordered) 1985 return getUNDEF(VT); 1986 // fall through 1987 case ISD::SETOGE: return getConstant(R==APFloat::cmpGreaterThan || 1988 R==APFloat::cmpEqual, dl, VT); 1989 case ISD::SETO: return getConstant(R!=APFloat::cmpUnordered, dl, VT); 1990 case ISD::SETUO: return getConstant(R==APFloat::cmpUnordered, dl, VT); 1991 case ISD::SETUEQ: return getConstant(R==APFloat::cmpUnordered || 1992 R==APFloat::cmpEqual, dl, VT); 1993 case ISD::SETUNE: return getConstant(R!=APFloat::cmpEqual, dl, VT); 1994 case ISD::SETULT: return getConstant(R==APFloat::cmpUnordered || 1995 R==APFloat::cmpLessThan, dl, VT); 1996 case ISD::SETUGT: return getConstant(R==APFloat::cmpGreaterThan || 1997 R==APFloat::cmpUnordered, dl, VT); 1998 case ISD::SETULE: return getConstant(R!=APFloat::cmpGreaterThan, dl, VT); 1999 case ISD::SETUGE: return getConstant(R!=APFloat::cmpLessThan, dl, VT); 2000 } 2001 } else { 2002 // Ensure that the constant occurs on the RHS. 2003 ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond); 2004 MVT CompVT = N1.getValueType().getSimpleVT(); 2005 if (!TLI->isCondCodeLegal(SwappedCond, CompVT)) 2006 return SDValue(); 2007 2008 return getSetCC(dl, VT, N2, N1, SwappedCond); 2009 } 2010 } 2011 2012 // Could not fold it. 2013 return SDValue(); 2014 } 2015 2016 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We 2017 /// use this predicate to simplify operations downstream. 2018 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const { 2019 // This predicate is not safe for vector operations. 2020 if (Op.getValueType().isVector()) 2021 return false; 2022 2023 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits(); 2024 return MaskedValueIsZero(Op, APInt::getSignBit(BitWidth), Depth); 2025 } 2026 2027 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use 2028 /// this predicate to simplify operations downstream. Mask is known to be zero 2029 /// for bits that V cannot have. 2030 bool SelectionDAG::MaskedValueIsZero(SDValue Op, const APInt &Mask, 2031 unsigned Depth) const { 2032 APInt KnownZero, KnownOne; 2033 computeKnownBits(Op, KnownZero, KnownOne, Depth); 2034 return (KnownZero & Mask) == Mask; 2035 } 2036 2037 /// Determine which bits of Op are known to be either zero or one and return 2038 /// them in the KnownZero/KnownOne bitsets. 2039 void SelectionDAG::computeKnownBits(SDValue Op, APInt &KnownZero, 2040 APInt &KnownOne, unsigned Depth) const { 2041 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits(); 2042 2043 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything. 2044 if (Depth == 6) 2045 return; // Limit search depth. 2046 2047 APInt KnownZero2, KnownOne2; 2048 2049 switch (Op.getOpcode()) { 2050 case ISD::Constant: 2051 // We know all of the bits for a constant! 2052 KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue(); 2053 KnownZero = ~KnownOne; 2054 break; 2055 case ISD::AND: 2056 // If either the LHS or the RHS are Zero, the result is zero. 2057 computeKnownBits(Op.getOperand(1), KnownZero, KnownOne, Depth+1); 2058 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1); 2059 2060 // Output known-1 bits are only known if set in both the LHS & RHS. 2061 KnownOne &= KnownOne2; 2062 // Output known-0 are known to be clear if zero in either the LHS | RHS. 2063 KnownZero |= KnownZero2; 2064 break; 2065 case ISD::OR: 2066 computeKnownBits(Op.getOperand(1), KnownZero, KnownOne, Depth+1); 2067 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1); 2068 2069 // Output known-0 bits are only known if clear in both the LHS & RHS. 2070 KnownZero &= KnownZero2; 2071 // Output known-1 are known to be set if set in either the LHS | RHS. 2072 KnownOne |= KnownOne2; 2073 break; 2074 case ISD::XOR: { 2075 computeKnownBits(Op.getOperand(1), KnownZero, KnownOne, Depth+1); 2076 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1); 2077 2078 // Output known-0 bits are known if clear or set in both the LHS & RHS. 2079 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2); 2080 // Output known-1 are known to be set if set in only one of the LHS, RHS. 2081 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2); 2082 KnownZero = KnownZeroOut; 2083 break; 2084 } 2085 case ISD::MUL: { 2086 computeKnownBits(Op.getOperand(1), KnownZero, KnownOne, Depth+1); 2087 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1); 2088 2089 // If low bits are zero in either operand, output low known-0 bits. 2090 // Also compute a conserative estimate for high known-0 bits. 2091 // More trickiness is possible, but this is sufficient for the 2092 // interesting case of alignment computation. 2093 KnownOne.clearAllBits(); 2094 unsigned TrailZ = KnownZero.countTrailingOnes() + 2095 KnownZero2.countTrailingOnes(); 2096 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() + 2097 KnownZero2.countLeadingOnes(), 2098 BitWidth) - BitWidth; 2099 2100 TrailZ = std::min(TrailZ, BitWidth); 2101 LeadZ = std::min(LeadZ, BitWidth); 2102 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) | 2103 APInt::getHighBitsSet(BitWidth, LeadZ); 2104 break; 2105 } 2106 case ISD::UDIV: { 2107 // For the purposes of computing leading zeros we can conservatively 2108 // treat a udiv as a logical right shift by the power of 2 known to 2109 // be less than the denominator. 2110 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1); 2111 unsigned LeadZ = KnownZero2.countLeadingOnes(); 2112 2113 KnownOne2.clearAllBits(); 2114 KnownZero2.clearAllBits(); 2115 computeKnownBits(Op.getOperand(1), KnownZero2, KnownOne2, Depth+1); 2116 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros(); 2117 if (RHSUnknownLeadingOnes != BitWidth) 2118 LeadZ = std::min(BitWidth, 2119 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1); 2120 2121 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ); 2122 break; 2123 } 2124 case ISD::SELECT: 2125 computeKnownBits(Op.getOperand(2), KnownZero, KnownOne, Depth+1); 2126 computeKnownBits(Op.getOperand(1), KnownZero2, KnownOne2, Depth+1); 2127 2128 // Only known if known in both the LHS and RHS. 2129 KnownOne &= KnownOne2; 2130 KnownZero &= KnownZero2; 2131 break; 2132 case ISD::SELECT_CC: 2133 computeKnownBits(Op.getOperand(3), KnownZero, KnownOne, Depth+1); 2134 computeKnownBits(Op.getOperand(2), KnownZero2, KnownOne2, Depth+1); 2135 2136 // Only known if known in both the LHS and RHS. 2137 KnownOne &= KnownOne2; 2138 KnownZero &= KnownZero2; 2139 break; 2140 case ISD::SADDO: 2141 case ISD::UADDO: 2142 case ISD::SSUBO: 2143 case ISD::USUBO: 2144 case ISD::SMULO: 2145 case ISD::UMULO: 2146 if (Op.getResNo() != 1) 2147 break; 2148 // The boolean result conforms to getBooleanContents. 2149 // If we know the result of a setcc has the top bits zero, use this info. 2150 // We know that we have an integer-based boolean since these operations 2151 // are only available for integer. 2152 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) == 2153 TargetLowering::ZeroOrOneBooleanContent && 2154 BitWidth > 1) 2155 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1); 2156 break; 2157 case ISD::SETCC: 2158 // If we know the result of a setcc has the top bits zero, use this info. 2159 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) == 2160 TargetLowering::ZeroOrOneBooleanContent && 2161 BitWidth > 1) 2162 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1); 2163 break; 2164 case ISD::SHL: 2165 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0 2166 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 2167 unsigned ShAmt = SA->getZExtValue(); 2168 2169 // If the shift count is an invalid immediate, don't do anything. 2170 if (ShAmt >= BitWidth) 2171 break; 2172 2173 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1); 2174 KnownZero <<= ShAmt; 2175 KnownOne <<= ShAmt; 2176 // low bits known zero. 2177 KnownZero |= APInt::getLowBitsSet(BitWidth, ShAmt); 2178 } 2179 break; 2180 case ISD::SRL: 2181 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0 2182 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 2183 unsigned ShAmt = SA->getZExtValue(); 2184 2185 // If the shift count is an invalid immediate, don't do anything. 2186 if (ShAmt >= BitWidth) 2187 break; 2188 2189 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1); 2190 KnownZero = KnownZero.lshr(ShAmt); 2191 KnownOne = KnownOne.lshr(ShAmt); 2192 2193 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt); 2194 KnownZero |= HighBits; // High bits known zero. 2195 } 2196 break; 2197 case ISD::SRA: 2198 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 2199 unsigned ShAmt = SA->getZExtValue(); 2200 2201 // If the shift count is an invalid immediate, don't do anything. 2202 if (ShAmt >= BitWidth) 2203 break; 2204 2205 // If any of the demanded bits are produced by the sign extension, we also 2206 // demand the input sign bit. 2207 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt); 2208 2209 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1); 2210 KnownZero = KnownZero.lshr(ShAmt); 2211 KnownOne = KnownOne.lshr(ShAmt); 2212 2213 // Handle the sign bits. 2214 APInt SignBit = APInt::getSignBit(BitWidth); 2215 SignBit = SignBit.lshr(ShAmt); // Adjust to where it is now in the mask. 2216 2217 if (KnownZero.intersects(SignBit)) { 2218 KnownZero |= HighBits; // New bits are known zero. 2219 } else if (KnownOne.intersects(SignBit)) { 2220 KnownOne |= HighBits; // New bits are known one. 2221 } 2222 } 2223 break; 2224 case ISD::SIGN_EXTEND_INREG: { 2225 EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 2226 unsigned EBits = EVT.getScalarType().getSizeInBits(); 2227 2228 // Sign extension. Compute the demanded bits in the result that are not 2229 // present in the input. 2230 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - EBits); 2231 2232 APInt InSignBit = APInt::getSignBit(EBits); 2233 APInt InputDemandedBits = APInt::getLowBitsSet(BitWidth, EBits); 2234 2235 // If the sign extended bits are demanded, we know that the sign 2236 // bit is demanded. 2237 InSignBit = InSignBit.zext(BitWidth); 2238 if (NewBits.getBoolValue()) 2239 InputDemandedBits |= InSignBit; 2240 2241 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1); 2242 KnownOne &= InputDemandedBits; 2243 KnownZero &= InputDemandedBits; 2244 2245 // If the sign bit of the input is known set or clear, then we know the 2246 // top bits of the result. 2247 if (KnownZero.intersects(InSignBit)) { // Input sign bit known clear 2248 KnownZero |= NewBits; 2249 KnownOne &= ~NewBits; 2250 } else if (KnownOne.intersects(InSignBit)) { // Input sign bit known set 2251 KnownOne |= NewBits; 2252 KnownZero &= ~NewBits; 2253 } else { // Input sign bit unknown 2254 KnownZero &= ~NewBits; 2255 KnownOne &= ~NewBits; 2256 } 2257 break; 2258 } 2259 case ISD::CTTZ: 2260 case ISD::CTTZ_ZERO_UNDEF: 2261 case ISD::CTLZ: 2262 case ISD::CTLZ_ZERO_UNDEF: 2263 case ISD::CTPOP: { 2264 unsigned LowBits = Log2_32(BitWidth)+1; 2265 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits); 2266 KnownOne.clearAllBits(); 2267 break; 2268 } 2269 case ISD::LOAD: { 2270 LoadSDNode *LD = cast<LoadSDNode>(Op); 2271 // If this is a ZEXTLoad and we are looking at the loaded value. 2272 if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) { 2273 EVT VT = LD->getMemoryVT(); 2274 unsigned MemBits = VT.getScalarType().getSizeInBits(); 2275 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits); 2276 } else if (const MDNode *Ranges = LD->getRanges()) { 2277 if (LD->getExtensionType() == ISD::NON_EXTLOAD) 2278 computeKnownBitsFromRangeMetadata(*Ranges, KnownZero, KnownOne); 2279 } 2280 break; 2281 } 2282 case ISD::ZERO_EXTEND: { 2283 EVT InVT = Op.getOperand(0).getValueType(); 2284 unsigned InBits = InVT.getScalarType().getSizeInBits(); 2285 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits); 2286 KnownZero = KnownZero.trunc(InBits); 2287 KnownOne = KnownOne.trunc(InBits); 2288 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1); 2289 KnownZero = KnownZero.zext(BitWidth); 2290 KnownOne = KnownOne.zext(BitWidth); 2291 KnownZero |= NewBits; 2292 break; 2293 } 2294 case ISD::SIGN_EXTEND: { 2295 EVT InVT = Op.getOperand(0).getValueType(); 2296 unsigned InBits = InVT.getScalarType().getSizeInBits(); 2297 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits); 2298 2299 KnownZero = KnownZero.trunc(InBits); 2300 KnownOne = KnownOne.trunc(InBits); 2301 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1); 2302 2303 // Note if the sign bit is known to be zero or one. 2304 bool SignBitKnownZero = KnownZero.isNegative(); 2305 bool SignBitKnownOne = KnownOne.isNegative(); 2306 2307 KnownZero = KnownZero.zext(BitWidth); 2308 KnownOne = KnownOne.zext(BitWidth); 2309 2310 // If the sign bit is known zero or one, the top bits match. 2311 if (SignBitKnownZero) 2312 KnownZero |= NewBits; 2313 else if (SignBitKnownOne) 2314 KnownOne |= NewBits; 2315 break; 2316 } 2317 case ISD::ANY_EXTEND: { 2318 EVT InVT = Op.getOperand(0).getValueType(); 2319 unsigned InBits = InVT.getScalarType().getSizeInBits(); 2320 KnownZero = KnownZero.trunc(InBits); 2321 KnownOne = KnownOne.trunc(InBits); 2322 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1); 2323 KnownZero = KnownZero.zext(BitWidth); 2324 KnownOne = KnownOne.zext(BitWidth); 2325 break; 2326 } 2327 case ISD::TRUNCATE: { 2328 EVT InVT = Op.getOperand(0).getValueType(); 2329 unsigned InBits = InVT.getScalarType().getSizeInBits(); 2330 KnownZero = KnownZero.zext(InBits); 2331 KnownOne = KnownOne.zext(InBits); 2332 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1); 2333 KnownZero = KnownZero.trunc(BitWidth); 2334 KnownOne = KnownOne.trunc(BitWidth); 2335 break; 2336 } 2337 case ISD::AssertZext: { 2338 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 2339 APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits()); 2340 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1); 2341 KnownZero |= (~InMask); 2342 KnownOne &= (~KnownZero); 2343 break; 2344 } 2345 case ISD::FGETSIGN: 2346 // All bits are zero except the low bit. 2347 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - 1); 2348 break; 2349 2350 case ISD::SUB: { 2351 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0))) { 2352 // We know that the top bits of C-X are clear if X contains less bits 2353 // than C (i.e. no wrap-around can happen). For example, 20-X is 2354 // positive if we can prove that X is >= 0 and < 16. 2355 if (CLHS->getAPIntValue().isNonNegative()) { 2356 unsigned NLZ = (CLHS->getAPIntValue()+1).countLeadingZeros(); 2357 // NLZ can't be BitWidth with no sign bit 2358 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1); 2359 computeKnownBits(Op.getOperand(1), KnownZero2, KnownOne2, Depth+1); 2360 2361 // If all of the MaskV bits are known to be zero, then we know the 2362 // output top bits are zero, because we now know that the output is 2363 // from [0-C]. 2364 if ((KnownZero2 & MaskV) == MaskV) { 2365 unsigned NLZ2 = CLHS->getAPIntValue().countLeadingZeros(); 2366 // Top bits known zero. 2367 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2); 2368 } 2369 } 2370 } 2371 } 2372 // fall through 2373 case ISD::ADD: 2374 case ISD::ADDE: { 2375 // Output known-0 bits are known if clear or set in both the low clear bits 2376 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the 2377 // low 3 bits clear. 2378 // Output known-0 bits are also known if the top bits of each input are 2379 // known to be clear. For example, if one input has the top 10 bits clear 2380 // and the other has the top 8 bits clear, we know the top 7 bits of the 2381 // output must be clear. 2382 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1); 2383 unsigned KnownZeroHigh = KnownZero2.countLeadingOnes(); 2384 unsigned KnownZeroLow = KnownZero2.countTrailingOnes(); 2385 2386 computeKnownBits(Op.getOperand(1), KnownZero2, KnownOne2, Depth+1); 2387 KnownZeroHigh = std::min(KnownZeroHigh, 2388 KnownZero2.countLeadingOnes()); 2389 KnownZeroLow = std::min(KnownZeroLow, 2390 KnownZero2.countTrailingOnes()); 2391 2392 if (Op.getOpcode() == ISD::ADD) { 2393 KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroLow); 2394 if (KnownZeroHigh > 1) 2395 KnownZero |= APInt::getHighBitsSet(BitWidth, KnownZeroHigh - 1); 2396 break; 2397 } 2398 2399 // With ADDE, a carry bit may be added in, so we can only use this 2400 // information if we know (at least) that the low two bits are clear. We 2401 // then return to the caller that the low bit is unknown but that other bits 2402 // are known zero. 2403 if (KnownZeroLow >= 2) // ADDE 2404 KnownZero |= APInt::getBitsSet(BitWidth, 1, KnownZeroLow); 2405 break; 2406 } 2407 case ISD::SREM: 2408 if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 2409 const APInt &RA = Rem->getAPIntValue().abs(); 2410 if (RA.isPowerOf2()) { 2411 APInt LowBits = RA - 1; 2412 computeKnownBits(Op.getOperand(0), KnownZero2,KnownOne2,Depth+1); 2413 2414 // The low bits of the first operand are unchanged by the srem. 2415 KnownZero = KnownZero2 & LowBits; 2416 KnownOne = KnownOne2 & LowBits; 2417 2418 // If the first operand is non-negative or has all low bits zero, then 2419 // the upper bits are all zero. 2420 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits)) 2421 KnownZero |= ~LowBits; 2422 2423 // If the first operand is negative and not all low bits are zero, then 2424 // the upper bits are all one. 2425 if (KnownOne2[BitWidth-1] && ((KnownOne2 & LowBits) != 0)) 2426 KnownOne |= ~LowBits; 2427 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 2428 } 2429 } 2430 break; 2431 case ISD::UREM: { 2432 if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 2433 const APInt &RA = Rem->getAPIntValue(); 2434 if (RA.isPowerOf2()) { 2435 APInt LowBits = (RA - 1); 2436 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth + 1); 2437 2438 // The upper bits are all zero, the lower ones are unchanged. 2439 KnownZero = KnownZero2 | ~LowBits; 2440 KnownOne = KnownOne2 & LowBits; 2441 break; 2442 } 2443 } 2444 2445 // Since the result is less than or equal to either operand, any leading 2446 // zero bits in either operand must also exist in the result. 2447 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1); 2448 computeKnownBits(Op.getOperand(1), KnownZero2, KnownOne2, Depth+1); 2449 2450 uint32_t Leaders = std::max(KnownZero.countLeadingOnes(), 2451 KnownZero2.countLeadingOnes()); 2452 KnownOne.clearAllBits(); 2453 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders); 2454 break; 2455 } 2456 case ISD::EXTRACT_ELEMENT: { 2457 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1); 2458 const unsigned Index = 2459 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 2460 const unsigned BitWidth = Op.getValueType().getSizeInBits(); 2461 2462 // Remove low part of known bits mask 2463 KnownZero = KnownZero.getHiBits(KnownZero.getBitWidth() - Index * BitWidth); 2464 KnownOne = KnownOne.getHiBits(KnownOne.getBitWidth() - Index * BitWidth); 2465 2466 // Remove high part of known bit mask 2467 KnownZero = KnownZero.trunc(BitWidth); 2468 KnownOne = KnownOne.trunc(BitWidth); 2469 break; 2470 } 2471 case ISD::SMIN: 2472 case ISD::SMAX: 2473 case ISD::UMIN: 2474 case ISD::UMAX: { 2475 APInt Op0Zero, Op0One; 2476 APInt Op1Zero, Op1One; 2477 computeKnownBits(Op.getOperand(0), Op0Zero, Op0One, Depth); 2478 computeKnownBits(Op.getOperand(1), Op1Zero, Op1One, Depth); 2479 2480 KnownZero = Op0Zero & Op1Zero; 2481 KnownOne = Op0One & Op1One; 2482 break; 2483 } 2484 case ISD::FrameIndex: 2485 case ISD::TargetFrameIndex: 2486 if (unsigned Align = InferPtrAlignment(Op)) { 2487 // The low bits are known zero if the pointer is aligned. 2488 KnownZero = APInt::getLowBitsSet(BitWidth, Log2_32(Align)); 2489 break; 2490 } 2491 break; 2492 2493 default: 2494 if (Op.getOpcode() < ISD::BUILTIN_OP_END) 2495 break; 2496 // Fallthrough 2497 case ISD::INTRINSIC_WO_CHAIN: 2498 case ISD::INTRINSIC_W_CHAIN: 2499 case ISD::INTRINSIC_VOID: 2500 // Allow the target to implement this method for its nodes. 2501 TLI->computeKnownBitsForTargetNode(Op, KnownZero, KnownOne, *this, Depth); 2502 break; 2503 } 2504 2505 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 2506 } 2507 2508 /// ComputeNumSignBits - Return the number of times the sign bit of the 2509 /// register is replicated into the other bits. We know that at least 1 bit 2510 /// is always equal to the sign bit (itself), but other cases can give us 2511 /// information. For example, immediately after an "SRA X, 2", we know that 2512 /// the top 3 bits are all equal to each other, so we return 3. 2513 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const{ 2514 EVT VT = Op.getValueType(); 2515 assert(VT.isInteger() && "Invalid VT!"); 2516 unsigned VTBits = VT.getScalarType().getSizeInBits(); 2517 unsigned Tmp, Tmp2; 2518 unsigned FirstAnswer = 1; 2519 2520 if (Depth == 6) 2521 return 1; // Limit search depth. 2522 2523 switch (Op.getOpcode()) { 2524 default: break; 2525 case ISD::AssertSext: 2526 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits(); 2527 return VTBits-Tmp+1; 2528 case ISD::AssertZext: 2529 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits(); 2530 return VTBits-Tmp; 2531 2532 case ISD::Constant: { 2533 const APInt &Val = cast<ConstantSDNode>(Op)->getAPIntValue(); 2534 return Val.getNumSignBits(); 2535 } 2536 2537 case ISD::SIGN_EXTEND: 2538 Tmp = 2539 VTBits-Op.getOperand(0).getValueType().getScalarType().getSizeInBits(); 2540 return ComputeNumSignBits(Op.getOperand(0), Depth+1) + Tmp; 2541 2542 case ISD::SIGN_EXTEND_INREG: 2543 // Max of the input and what this extends. 2544 Tmp = 2545 cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarType().getSizeInBits(); 2546 Tmp = VTBits-Tmp+1; 2547 2548 Tmp2 = ComputeNumSignBits(Op.getOperand(0), Depth+1); 2549 return std::max(Tmp, Tmp2); 2550 2551 case ISD::SRA: 2552 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1); 2553 // SRA X, C -> adds C sign bits. 2554 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 2555 Tmp += C->getZExtValue(); 2556 if (Tmp > VTBits) Tmp = VTBits; 2557 } 2558 return Tmp; 2559 case ISD::SHL: 2560 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 2561 // shl destroys sign bits. 2562 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1); 2563 if (C->getZExtValue() >= VTBits || // Bad shift. 2564 C->getZExtValue() >= Tmp) break; // Shifted all sign bits out. 2565 return Tmp - C->getZExtValue(); 2566 } 2567 break; 2568 case ISD::AND: 2569 case ISD::OR: 2570 case ISD::XOR: // NOT is handled here. 2571 // Logical binary ops preserve the number of sign bits at the worst. 2572 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1); 2573 if (Tmp != 1) { 2574 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1); 2575 FirstAnswer = std::min(Tmp, Tmp2); 2576 // We computed what we know about the sign bits as our first 2577 // answer. Now proceed to the generic code that uses 2578 // computeKnownBits, and pick whichever answer is better. 2579 } 2580 break; 2581 2582 case ISD::SELECT: 2583 Tmp = ComputeNumSignBits(Op.getOperand(1), Depth+1); 2584 if (Tmp == 1) return 1; // Early out. 2585 Tmp2 = ComputeNumSignBits(Op.getOperand(2), Depth+1); 2586 return std::min(Tmp, Tmp2); 2587 case ISD::SELECT_CC: 2588 Tmp = ComputeNumSignBits(Op.getOperand(2), Depth+1); 2589 if (Tmp == 1) return 1; // Early out. 2590 Tmp2 = ComputeNumSignBits(Op.getOperand(3), Depth+1); 2591 return std::min(Tmp, Tmp2); 2592 case ISD::SMIN: 2593 case ISD::SMAX: 2594 case ISD::UMIN: 2595 case ISD::UMAX: 2596 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth + 1); 2597 if (Tmp == 1) 2598 return 1; // Early out. 2599 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth + 1); 2600 return std::min(Tmp, Tmp2); 2601 case ISD::SADDO: 2602 case ISD::UADDO: 2603 case ISD::SSUBO: 2604 case ISD::USUBO: 2605 case ISD::SMULO: 2606 case ISD::UMULO: 2607 if (Op.getResNo() != 1) 2608 break; 2609 // The boolean result conforms to getBooleanContents. Fall through. 2610 // If setcc returns 0/-1, all bits are sign bits. 2611 // We know that we have an integer-based boolean since these operations 2612 // are only available for integer. 2613 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) == 2614 TargetLowering::ZeroOrNegativeOneBooleanContent) 2615 return VTBits; 2616 break; 2617 case ISD::SETCC: 2618 // If setcc returns 0/-1, all bits are sign bits. 2619 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) == 2620 TargetLowering::ZeroOrNegativeOneBooleanContent) 2621 return VTBits; 2622 break; 2623 case ISD::ROTL: 2624 case ISD::ROTR: 2625 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 2626 unsigned RotAmt = C->getZExtValue() & (VTBits-1); 2627 2628 // Handle rotate right by N like a rotate left by 32-N. 2629 if (Op.getOpcode() == ISD::ROTR) 2630 RotAmt = (VTBits-RotAmt) & (VTBits-1); 2631 2632 // If we aren't rotating out all of the known-in sign bits, return the 2633 // number that are left. This handles rotl(sext(x), 1) for example. 2634 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1); 2635 if (Tmp > RotAmt+1) return Tmp-RotAmt; 2636 } 2637 break; 2638 case ISD::ADD: 2639 // Add can have at most one carry bit. Thus we know that the output 2640 // is, at worst, one more bit than the inputs. 2641 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1); 2642 if (Tmp == 1) return 1; // Early out. 2643 2644 // Special case decrementing a value (ADD X, -1): 2645 if (ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 2646 if (CRHS->isAllOnesValue()) { 2647 APInt KnownZero, KnownOne; 2648 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1); 2649 2650 // If the input is known to be 0 or 1, the output is 0/-1, which is all 2651 // sign bits set. 2652 if ((KnownZero | APInt(VTBits, 1)).isAllOnesValue()) 2653 return VTBits; 2654 2655 // If we are subtracting one from a positive number, there is no carry 2656 // out of the result. 2657 if (KnownZero.isNegative()) 2658 return Tmp; 2659 } 2660 2661 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1); 2662 if (Tmp2 == 1) return 1; 2663 return std::min(Tmp, Tmp2)-1; 2664 2665 case ISD::SUB: 2666 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1); 2667 if (Tmp2 == 1) return 1; 2668 2669 // Handle NEG. 2670 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0))) 2671 if (CLHS->isNullValue()) { 2672 APInt KnownZero, KnownOne; 2673 computeKnownBits(Op.getOperand(1), KnownZero, KnownOne, Depth+1); 2674 // If the input is known to be 0 or 1, the output is 0/-1, which is all 2675 // sign bits set. 2676 if ((KnownZero | APInt(VTBits, 1)).isAllOnesValue()) 2677 return VTBits; 2678 2679 // If the input is known to be positive (the sign bit is known clear), 2680 // the output of the NEG has the same number of sign bits as the input. 2681 if (KnownZero.isNegative()) 2682 return Tmp2; 2683 2684 // Otherwise, we treat this like a SUB. 2685 } 2686 2687 // Sub can have at most one carry bit. Thus we know that the output 2688 // is, at worst, one more bit than the inputs. 2689 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1); 2690 if (Tmp == 1) return 1; // Early out. 2691 return std::min(Tmp, Tmp2)-1; 2692 case ISD::TRUNCATE: 2693 // FIXME: it's tricky to do anything useful for this, but it is an important 2694 // case for targets like X86. 2695 break; 2696 case ISD::EXTRACT_ELEMENT: { 2697 const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1); 2698 const int BitWidth = Op.getValueType().getSizeInBits(); 2699 const int Items = 2700 Op.getOperand(0).getValueType().getSizeInBits() / BitWidth; 2701 2702 // Get reverse index (starting from 1), Op1 value indexes elements from 2703 // little end. Sign starts at big end. 2704 const int rIndex = Items - 1 - 2705 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 2706 2707 // If the sign portion ends in our element the subtraction gives correct 2708 // result. Otherwise it gives either negative or > bitwidth result 2709 return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0); 2710 } 2711 } 2712 2713 // If we are looking at the loaded value of the SDNode. 2714 if (Op.getResNo() == 0) { 2715 // Handle LOADX separately here. EXTLOAD case will fallthrough. 2716 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) { 2717 unsigned ExtType = LD->getExtensionType(); 2718 switch (ExtType) { 2719 default: break; 2720 case ISD::SEXTLOAD: // '17' bits known 2721 Tmp = LD->getMemoryVT().getScalarType().getSizeInBits(); 2722 return VTBits-Tmp+1; 2723 case ISD::ZEXTLOAD: // '16' bits known 2724 Tmp = LD->getMemoryVT().getScalarType().getSizeInBits(); 2725 return VTBits-Tmp; 2726 } 2727 } 2728 } 2729 2730 // Allow the target to implement this method for its nodes. 2731 if (Op.getOpcode() >= ISD::BUILTIN_OP_END || 2732 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 2733 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 2734 Op.getOpcode() == ISD::INTRINSIC_VOID) { 2735 unsigned NumBits = TLI->ComputeNumSignBitsForTargetNode(Op, *this, Depth); 2736 if (NumBits > 1) FirstAnswer = std::max(FirstAnswer, NumBits); 2737 } 2738 2739 // Finally, if we can prove that the top bits of the result are 0's or 1's, 2740 // use this information. 2741 APInt KnownZero, KnownOne; 2742 computeKnownBits(Op, KnownZero, KnownOne, Depth); 2743 2744 APInt Mask; 2745 if (KnownZero.isNegative()) { // sign bit is 0 2746 Mask = KnownZero; 2747 } else if (KnownOne.isNegative()) { // sign bit is 1; 2748 Mask = KnownOne; 2749 } else { 2750 // Nothing known. 2751 return FirstAnswer; 2752 } 2753 2754 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine 2755 // the number of identical bits in the top of the input value. 2756 Mask = ~Mask; 2757 Mask <<= Mask.getBitWidth()-VTBits; 2758 // Return # leading zeros. We use 'min' here in case Val was zero before 2759 // shifting. We don't want to return '64' as for an i32 "0". 2760 return std::max(FirstAnswer, std::min(VTBits, Mask.countLeadingZeros())); 2761 } 2762 2763 /// isBaseWithConstantOffset - Return true if the specified operand is an 2764 /// ISD::ADD with a ConstantSDNode on the right-hand side, or if it is an 2765 /// ISD::OR with a ConstantSDNode that is guaranteed to have the same 2766 /// semantics as an ADD. This handles the equivalence: 2767 /// X|Cst == X+Cst iff X&Cst = 0. 2768 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const { 2769 if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) || 2770 !isa<ConstantSDNode>(Op.getOperand(1))) 2771 return false; 2772 2773 if (Op.getOpcode() == ISD::OR && 2774 !MaskedValueIsZero(Op.getOperand(0), 2775 cast<ConstantSDNode>(Op.getOperand(1))->getAPIntValue())) 2776 return false; 2777 2778 return true; 2779 } 2780 2781 2782 bool SelectionDAG::isKnownNeverNaN(SDValue Op) const { 2783 // If we're told that NaNs won't happen, assume they won't. 2784 if (getTarget().Options.NoNaNsFPMath) 2785 return true; 2786 2787 // If the value is a constant, we can obviously see if it is a NaN or not. 2788 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 2789 return !C->getValueAPF().isNaN(); 2790 2791 // TODO: Recognize more cases here. 2792 2793 return false; 2794 } 2795 2796 bool SelectionDAG::isKnownNeverZero(SDValue Op) const { 2797 // If the value is a constant, we can obviously see if it is a zero or not. 2798 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 2799 return !C->isZero(); 2800 2801 // TODO: Recognize more cases here. 2802 switch (Op.getOpcode()) { 2803 default: break; 2804 case ISD::OR: 2805 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 2806 return !C->isNullValue(); 2807 break; 2808 } 2809 2810 return false; 2811 } 2812 2813 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const { 2814 // Check the obvious case. 2815 if (A == B) return true; 2816 2817 // For for negative and positive zero. 2818 if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) 2819 if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) 2820 if (CA->isZero() && CB->isZero()) return true; 2821 2822 // Otherwise they may not be equal. 2823 return false; 2824 } 2825 2826 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const { 2827 assert(A.getValueType() == B.getValueType() && 2828 "Values must have the same type"); 2829 APInt AZero, AOne; 2830 APInt BZero, BOne; 2831 computeKnownBits(A, AZero, AOne); 2832 computeKnownBits(B, BZero, BOne); 2833 return (AZero | BZero).isAllOnesValue(); 2834 } 2835 2836 static SDValue FoldCONCAT_VECTORS(SDLoc DL, EVT VT, ArrayRef<SDValue> Ops, 2837 llvm::SelectionDAG &DAG) { 2838 if (Ops.size() == 1) 2839 return Ops[0]; 2840 2841 // Concat of UNDEFs is UNDEF. 2842 if (std::all_of(Ops.begin(), Ops.end(), 2843 [](SDValue Op) { return Op.isUndef(); })) 2844 return DAG.getUNDEF(VT); 2845 2846 // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be 2847 // simplified to one big BUILD_VECTOR. 2848 // FIXME: Add support for SCALAR_TO_VECTOR as well. 2849 EVT SVT = VT.getScalarType(); 2850 SmallVector<SDValue, 16> Elts; 2851 for (SDValue Op : Ops) { 2852 EVT OpVT = Op.getValueType(); 2853 if (Op.isUndef()) 2854 Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT)); 2855 else if (Op.getOpcode() == ISD::BUILD_VECTOR) 2856 Elts.append(Op->op_begin(), Op->op_end()); 2857 else 2858 return SDValue(); 2859 } 2860 2861 // BUILD_VECTOR requires all inputs to be of the same type, find the 2862 // maximum type and extend them all. 2863 for (SDValue Op : Elts) 2864 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT); 2865 2866 if (SVT.bitsGT(VT.getScalarType())) 2867 for (SDValue &Op : Elts) 2868 Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT) 2869 ? DAG.getZExtOrTrunc(Op, DL, SVT) 2870 : DAG.getSExtOrTrunc(Op, DL, SVT); 2871 2872 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts); 2873 } 2874 2875 /// getNode - Gets or creates the specified node. 2876 /// 2877 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, EVT VT) { 2878 FoldingSetNodeID ID; 2879 AddNodeIDNode(ID, Opcode, getVTList(VT), None); 2880 void *IP = nullptr; 2881 if (SDNode *E = FindNodeOrInsertPos(ID, DL.getDebugLoc(), IP)) 2882 return SDValue(E, 0); 2883 2884 SDNode *N = new (NodeAllocator) SDNode(Opcode, DL.getIROrder(), 2885 DL.getDebugLoc(), getVTList(VT)); 2886 CSEMap.InsertNode(N, IP); 2887 2888 InsertNode(N); 2889 return SDValue(N, 0); 2890 } 2891 2892 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, 2893 EVT VT, SDValue Operand) { 2894 // Constant fold unary operations with an integer constant operand. Even 2895 // opaque constant will be folded, because the folding of unary operations 2896 // doesn't create new constants with different values. Nevertheless, the 2897 // opaque flag is preserved during folding to prevent future folding with 2898 // other constants. 2899 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) { 2900 const APInt &Val = C->getAPIntValue(); 2901 switch (Opcode) { 2902 default: break; 2903 case ISD::SIGN_EXTEND: 2904 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT, 2905 C->isTargetOpcode(), C->isOpaque()); 2906 case ISD::ANY_EXTEND: 2907 case ISD::ZERO_EXTEND: 2908 case ISD::TRUNCATE: 2909 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT, 2910 C->isTargetOpcode(), C->isOpaque()); 2911 case ISD::UINT_TO_FP: 2912 case ISD::SINT_TO_FP: { 2913 APFloat apf(EVTToAPFloatSemantics(VT), 2914 APInt::getNullValue(VT.getSizeInBits())); 2915 (void)apf.convertFromAPInt(Val, 2916 Opcode==ISD::SINT_TO_FP, 2917 APFloat::rmNearestTiesToEven); 2918 return getConstantFP(apf, DL, VT); 2919 } 2920 case ISD::BITCAST: 2921 if (VT == MVT::f16 && C->getValueType(0) == MVT::i16) 2922 return getConstantFP(APFloat(APFloat::IEEEhalf, Val), DL, VT); 2923 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32) 2924 return getConstantFP(APFloat(APFloat::IEEEsingle, Val), DL, VT); 2925 if (VT == MVT::f64 && C->getValueType(0) == MVT::i64) 2926 return getConstantFP(APFloat(APFloat::IEEEdouble, Val), DL, VT); 2927 if (VT == MVT::f128 && C->getValueType(0) == MVT::i128) 2928 return getConstantFP(APFloat(APFloat::IEEEquad, Val), DL, VT); 2929 break; 2930 case ISD::BSWAP: 2931 return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(), 2932 C->isOpaque()); 2933 case ISD::CTPOP: 2934 return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(), 2935 C->isOpaque()); 2936 case ISD::CTLZ: 2937 case ISD::CTLZ_ZERO_UNDEF: 2938 return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(), 2939 C->isOpaque()); 2940 case ISD::CTTZ: 2941 case ISD::CTTZ_ZERO_UNDEF: 2942 return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(), 2943 C->isOpaque()); 2944 } 2945 } 2946 2947 // Constant fold unary operations with a floating point constant operand. 2948 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) { 2949 APFloat V = C->getValueAPF(); // make copy 2950 switch (Opcode) { 2951 case ISD::FNEG: 2952 V.changeSign(); 2953 return getConstantFP(V, DL, VT); 2954 case ISD::FABS: 2955 V.clearSign(); 2956 return getConstantFP(V, DL, VT); 2957 case ISD::FCEIL: { 2958 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive); 2959 if (fs == APFloat::opOK || fs == APFloat::opInexact) 2960 return getConstantFP(V, DL, VT); 2961 break; 2962 } 2963 case ISD::FTRUNC: { 2964 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero); 2965 if (fs == APFloat::opOK || fs == APFloat::opInexact) 2966 return getConstantFP(V, DL, VT); 2967 break; 2968 } 2969 case ISD::FFLOOR: { 2970 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative); 2971 if (fs == APFloat::opOK || fs == APFloat::opInexact) 2972 return getConstantFP(V, DL, VT); 2973 break; 2974 } 2975 case ISD::FP_EXTEND: { 2976 bool ignored; 2977 // This can return overflow, underflow, or inexact; we don't care. 2978 // FIXME need to be more flexible about rounding mode. 2979 (void)V.convert(EVTToAPFloatSemantics(VT), 2980 APFloat::rmNearestTiesToEven, &ignored); 2981 return getConstantFP(V, DL, VT); 2982 } 2983 case ISD::FP_TO_SINT: 2984 case ISD::FP_TO_UINT: { 2985 integerPart x[2]; 2986 bool ignored; 2987 static_assert(integerPartWidth >= 64, "APFloat parts too small!"); 2988 // FIXME need to be more flexible about rounding mode. 2989 APFloat::opStatus s = V.convertToInteger(x, VT.getSizeInBits(), 2990 Opcode==ISD::FP_TO_SINT, 2991 APFloat::rmTowardZero, &ignored); 2992 if (s==APFloat::opInvalidOp) // inexact is OK, in fact usual 2993 break; 2994 APInt api(VT.getSizeInBits(), x); 2995 return getConstant(api, DL, VT); 2996 } 2997 case ISD::BITCAST: 2998 if (VT == MVT::i16 && C->getValueType(0) == MVT::f16) 2999 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT); 3000 else if (VT == MVT::i32 && C->getValueType(0) == MVT::f32) 3001 return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT); 3002 else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64) 3003 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT); 3004 break; 3005 } 3006 } 3007 3008 // Constant fold unary operations with a vector integer or float operand. 3009 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Operand)) { 3010 if (BV->isConstant()) { 3011 switch (Opcode) { 3012 default: 3013 // FIXME: Entirely reasonable to perform folding of other unary 3014 // operations here as the need arises. 3015 break; 3016 case ISD::FNEG: 3017 case ISD::FABS: 3018 case ISD::FCEIL: 3019 case ISD::FTRUNC: 3020 case ISD::FFLOOR: 3021 case ISD::FP_EXTEND: 3022 case ISD::FP_TO_SINT: 3023 case ISD::FP_TO_UINT: 3024 case ISD::TRUNCATE: 3025 case ISD::UINT_TO_FP: 3026 case ISD::SINT_TO_FP: 3027 case ISD::BSWAP: 3028 case ISD::CTLZ: 3029 case ISD::CTLZ_ZERO_UNDEF: 3030 case ISD::CTTZ: 3031 case ISD::CTTZ_ZERO_UNDEF: 3032 case ISD::CTPOP: { 3033 SDValue Ops = { Operand }; 3034 if (SDValue Fold = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops)) 3035 return Fold; 3036 } 3037 } 3038 } 3039 } 3040 3041 unsigned OpOpcode = Operand.getNode()->getOpcode(); 3042 switch (Opcode) { 3043 case ISD::TokenFactor: 3044 case ISD::MERGE_VALUES: 3045 case ISD::CONCAT_VECTORS: 3046 return Operand; // Factor, merge or concat of one node? No need. 3047 case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node"); 3048 case ISD::FP_EXTEND: 3049 assert(VT.isFloatingPoint() && 3050 Operand.getValueType().isFloatingPoint() && "Invalid FP cast!"); 3051 if (Operand.getValueType() == VT) return Operand; // noop conversion. 3052 assert((!VT.isVector() || 3053 VT.getVectorNumElements() == 3054 Operand.getValueType().getVectorNumElements()) && 3055 "Vector element count mismatch!"); 3056 assert(Operand.getValueType().bitsLT(VT) && 3057 "Invalid fpext node, dst < src!"); 3058 if (Operand.getOpcode() == ISD::UNDEF) 3059 return getUNDEF(VT); 3060 break; 3061 case ISD::SIGN_EXTEND: 3062 assert(VT.isInteger() && Operand.getValueType().isInteger() && 3063 "Invalid SIGN_EXTEND!"); 3064 if (Operand.getValueType() == VT) return Operand; // noop extension 3065 assert((!VT.isVector() || 3066 VT.getVectorNumElements() == 3067 Operand.getValueType().getVectorNumElements()) && 3068 "Vector element count mismatch!"); 3069 assert(Operand.getValueType().bitsLT(VT) && 3070 "Invalid sext node, dst < src!"); 3071 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND) 3072 return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0)); 3073 else if (OpOpcode == ISD::UNDEF) 3074 // sext(undef) = 0, because the top bits will all be the same. 3075 return getConstant(0, DL, VT); 3076 break; 3077 case ISD::ZERO_EXTEND: 3078 assert(VT.isInteger() && Operand.getValueType().isInteger() && 3079 "Invalid ZERO_EXTEND!"); 3080 if (Operand.getValueType() == VT) return Operand; // noop extension 3081 assert((!VT.isVector() || 3082 VT.getVectorNumElements() == 3083 Operand.getValueType().getVectorNumElements()) && 3084 "Vector element count mismatch!"); 3085 assert(Operand.getValueType().bitsLT(VT) && 3086 "Invalid zext node, dst < src!"); 3087 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x) 3088 return getNode(ISD::ZERO_EXTEND, DL, VT, 3089 Operand.getNode()->getOperand(0)); 3090 else if (OpOpcode == ISD::UNDEF) 3091 // zext(undef) = 0, because the top bits will be zero. 3092 return getConstant(0, DL, VT); 3093 break; 3094 case ISD::ANY_EXTEND: 3095 assert(VT.isInteger() && Operand.getValueType().isInteger() && 3096 "Invalid ANY_EXTEND!"); 3097 if (Operand.getValueType() == VT) return Operand; // noop extension 3098 assert((!VT.isVector() || 3099 VT.getVectorNumElements() == 3100 Operand.getValueType().getVectorNumElements()) && 3101 "Vector element count mismatch!"); 3102 assert(Operand.getValueType().bitsLT(VT) && 3103 "Invalid anyext node, dst < src!"); 3104 3105 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND || 3106 OpOpcode == ISD::ANY_EXTEND) 3107 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x) 3108 return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0)); 3109 else if (OpOpcode == ISD::UNDEF) 3110 return getUNDEF(VT); 3111 3112 // (ext (trunx x)) -> x 3113 if (OpOpcode == ISD::TRUNCATE) { 3114 SDValue OpOp = Operand.getNode()->getOperand(0); 3115 if (OpOp.getValueType() == VT) 3116 return OpOp; 3117 } 3118 break; 3119 case ISD::TRUNCATE: 3120 assert(VT.isInteger() && Operand.getValueType().isInteger() && 3121 "Invalid TRUNCATE!"); 3122 if (Operand.getValueType() == VT) return Operand; // noop truncate 3123 assert((!VT.isVector() || 3124 VT.getVectorNumElements() == 3125 Operand.getValueType().getVectorNumElements()) && 3126 "Vector element count mismatch!"); 3127 assert(Operand.getValueType().bitsGT(VT) && 3128 "Invalid truncate node, src < dst!"); 3129 if (OpOpcode == ISD::TRUNCATE) 3130 return getNode(ISD::TRUNCATE, DL, VT, Operand.getNode()->getOperand(0)); 3131 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND || 3132 OpOpcode == ISD::ANY_EXTEND) { 3133 // If the source is smaller than the dest, we still need an extend. 3134 if (Operand.getNode()->getOperand(0).getValueType().getScalarType() 3135 .bitsLT(VT.getScalarType())) 3136 return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0)); 3137 if (Operand.getNode()->getOperand(0).getValueType().bitsGT(VT)) 3138 return getNode(ISD::TRUNCATE, DL, VT, Operand.getNode()->getOperand(0)); 3139 return Operand.getNode()->getOperand(0); 3140 } 3141 if (OpOpcode == ISD::UNDEF) 3142 return getUNDEF(VT); 3143 break; 3144 case ISD::BSWAP: 3145 assert(VT.isInteger() && VT == Operand.getValueType() && 3146 "Invalid BSWAP!"); 3147 assert((VT.getScalarSizeInBits() % 16 == 0) && 3148 "BSWAP types must be a multiple of 16 bits!"); 3149 if (OpOpcode == ISD::UNDEF) 3150 return getUNDEF(VT); 3151 break; 3152 case ISD::BITCAST: 3153 // Basic sanity checking. 3154 assert(VT.getSizeInBits() == Operand.getValueType().getSizeInBits() 3155 && "Cannot BITCAST between types of different sizes!"); 3156 if (VT == Operand.getValueType()) return Operand; // noop conversion. 3157 if (OpOpcode == ISD::BITCAST) // bitconv(bitconv(x)) -> bitconv(x) 3158 return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0)); 3159 if (OpOpcode == ISD::UNDEF) 3160 return getUNDEF(VT); 3161 break; 3162 case ISD::SCALAR_TO_VECTOR: 3163 assert(VT.isVector() && !Operand.getValueType().isVector() && 3164 (VT.getVectorElementType() == Operand.getValueType() || 3165 (VT.getVectorElementType().isInteger() && 3166 Operand.getValueType().isInteger() && 3167 VT.getVectorElementType().bitsLE(Operand.getValueType()))) && 3168 "Illegal SCALAR_TO_VECTOR node!"); 3169 if (OpOpcode == ISD::UNDEF) 3170 return getUNDEF(VT); 3171 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined. 3172 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT && 3173 isa<ConstantSDNode>(Operand.getOperand(1)) && 3174 Operand.getConstantOperandVal(1) == 0 && 3175 Operand.getOperand(0).getValueType() == VT) 3176 return Operand.getOperand(0); 3177 break; 3178 case ISD::FNEG: 3179 // -(X-Y) -> (Y-X) is unsafe because when X==Y, -0.0 != +0.0 3180 if (getTarget().Options.UnsafeFPMath && OpOpcode == ISD::FSUB) 3181 // FIXME: FNEG has no fast-math-flags to propagate; use the FSUB's flags? 3182 return getNode(ISD::FSUB, DL, VT, Operand.getNode()->getOperand(1), 3183 Operand.getNode()->getOperand(0), 3184 &cast<BinaryWithFlagsSDNode>(Operand.getNode())->Flags); 3185 if (OpOpcode == ISD::FNEG) // --X -> X 3186 return Operand.getNode()->getOperand(0); 3187 break; 3188 case ISD::FABS: 3189 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X) 3190 return getNode(ISD::FABS, DL, VT, Operand.getNode()->getOperand(0)); 3191 break; 3192 } 3193 3194 SDNode *N; 3195 SDVTList VTs = getVTList(VT); 3196 if (VT != MVT::Glue) { // Don't CSE flag producing nodes 3197 FoldingSetNodeID ID; 3198 SDValue Ops[1] = { Operand }; 3199 AddNodeIDNode(ID, Opcode, VTs, Ops); 3200 void *IP = nullptr; 3201 if (SDNode *E = FindNodeOrInsertPos(ID, DL.getDebugLoc(), IP)) 3202 return SDValue(E, 0); 3203 3204 N = new (NodeAllocator) UnarySDNode(Opcode, DL.getIROrder(), 3205 DL.getDebugLoc(), VTs, Operand); 3206 CSEMap.InsertNode(N, IP); 3207 } else { 3208 N = new (NodeAllocator) UnarySDNode(Opcode, DL.getIROrder(), 3209 DL.getDebugLoc(), VTs, Operand); 3210 } 3211 3212 InsertNode(N); 3213 return SDValue(N, 0); 3214 } 3215 3216 static std::pair<APInt, bool> FoldValue(unsigned Opcode, const APInt &C1, 3217 const APInt &C2) { 3218 switch (Opcode) { 3219 case ISD::ADD: return std::make_pair(C1 + C2, true); 3220 case ISD::SUB: return std::make_pair(C1 - C2, true); 3221 case ISD::MUL: return std::make_pair(C1 * C2, true); 3222 case ISD::AND: return std::make_pair(C1 & C2, true); 3223 case ISD::OR: return std::make_pair(C1 | C2, true); 3224 case ISD::XOR: return std::make_pair(C1 ^ C2, true); 3225 case ISD::SHL: return std::make_pair(C1 << C2, true); 3226 case ISD::SRL: return std::make_pair(C1.lshr(C2), true); 3227 case ISD::SRA: return std::make_pair(C1.ashr(C2), true); 3228 case ISD::ROTL: return std::make_pair(C1.rotl(C2), true); 3229 case ISD::ROTR: return std::make_pair(C1.rotr(C2), true); 3230 case ISD::SMIN: return std::make_pair(C1.sle(C2) ? C1 : C2, true); 3231 case ISD::SMAX: return std::make_pair(C1.sge(C2) ? C1 : C2, true); 3232 case ISD::UMIN: return std::make_pair(C1.ule(C2) ? C1 : C2, true); 3233 case ISD::UMAX: return std::make_pair(C1.uge(C2) ? C1 : C2, true); 3234 case ISD::UDIV: 3235 if (!C2.getBoolValue()) 3236 break; 3237 return std::make_pair(C1.udiv(C2), true); 3238 case ISD::UREM: 3239 if (!C2.getBoolValue()) 3240 break; 3241 return std::make_pair(C1.urem(C2), true); 3242 case ISD::SDIV: 3243 if (!C2.getBoolValue()) 3244 break; 3245 return std::make_pair(C1.sdiv(C2), true); 3246 case ISD::SREM: 3247 if (!C2.getBoolValue()) 3248 break; 3249 return std::make_pair(C1.srem(C2), true); 3250 } 3251 return std::make_pair(APInt(1, 0), false); 3252 } 3253 3254 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, SDLoc DL, EVT VT, 3255 const ConstantSDNode *Cst1, 3256 const ConstantSDNode *Cst2) { 3257 if (Cst1->isOpaque() || Cst2->isOpaque()) 3258 return SDValue(); 3259 3260 std::pair<APInt, bool> Folded = FoldValue(Opcode, Cst1->getAPIntValue(), 3261 Cst2->getAPIntValue()); 3262 if (!Folded.second) 3263 return SDValue(); 3264 return getConstant(Folded.first, DL, VT); 3265 } 3266 3267 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT, 3268 const GlobalAddressSDNode *GA, 3269 const SDNode *N2) { 3270 if (GA->getOpcode() != ISD::GlobalAddress) 3271 return SDValue(); 3272 if (!TLI->isOffsetFoldingLegal(GA)) 3273 return SDValue(); 3274 const ConstantSDNode *Cst2 = dyn_cast<ConstantSDNode>(N2); 3275 if (!Cst2) 3276 return SDValue(); 3277 int64_t Offset = Cst2->getSExtValue(); 3278 switch (Opcode) { 3279 case ISD::ADD: break; 3280 case ISD::SUB: Offset = -uint64_t(Offset); break; 3281 default: return SDValue(); 3282 } 3283 return getGlobalAddress(GA->getGlobal(), SDLoc(Cst2), VT, 3284 GA->getOffset() + uint64_t(Offset)); 3285 } 3286 3287 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, SDLoc DL, EVT VT, 3288 SDNode *Cst1, SDNode *Cst2) { 3289 // If the opcode is a target-specific ISD node, there's nothing we can 3290 // do here and the operand rules may not line up with the below, so 3291 // bail early. 3292 if (Opcode >= ISD::BUILTIN_OP_END) 3293 return SDValue(); 3294 3295 // Handle the case of two scalars. 3296 if (const ConstantSDNode *Scalar1 = dyn_cast<ConstantSDNode>(Cst1)) { 3297 if (const ConstantSDNode *Scalar2 = dyn_cast<ConstantSDNode>(Cst2)) { 3298 if (SDValue Folded = 3299 FoldConstantArithmetic(Opcode, DL, VT, Scalar1, Scalar2)) { 3300 if (!VT.isVector()) 3301 return Folded; 3302 SmallVector<SDValue, 4> Outputs; 3303 // We may have a vector type but a scalar result. Create a splat. 3304 Outputs.resize(VT.getVectorNumElements(), Outputs.back()); 3305 // Build a big vector out of the scalar elements we generated. 3306 return getNode(ISD::BUILD_VECTOR, SDLoc(), VT, Outputs); 3307 } else { 3308 return SDValue(); 3309 } 3310 } 3311 } 3312 3313 // fold (add Sym, c) -> Sym+c 3314 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Cst1)) 3315 return FoldSymbolOffset(Opcode, VT, GA, Cst2); 3316 if (isCommutativeBinOp(Opcode)) 3317 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Cst2)) 3318 return FoldSymbolOffset(Opcode, VT, GA, Cst1); 3319 3320 // For vectors extract each constant element into Inputs so we can constant 3321 // fold them individually. 3322 BuildVectorSDNode *BV1 = dyn_cast<BuildVectorSDNode>(Cst1); 3323 BuildVectorSDNode *BV2 = dyn_cast<BuildVectorSDNode>(Cst2); 3324 if (!BV1 || !BV2) 3325 return SDValue(); 3326 3327 assert(BV1->getNumOperands() == BV2->getNumOperands() && "Out of sync!"); 3328 3329 EVT SVT = VT.getScalarType(); 3330 SmallVector<SDValue, 4> Outputs; 3331 for (unsigned I = 0, E = BV1->getNumOperands(); I != E; ++I) { 3332 ConstantSDNode *V1 = dyn_cast<ConstantSDNode>(BV1->getOperand(I)); 3333 ConstantSDNode *V2 = dyn_cast<ConstantSDNode>(BV2->getOperand(I)); 3334 if (!V1 || !V2) // Not a constant, bail. 3335 return SDValue(); 3336 3337 if (V1->isOpaque() || V2->isOpaque()) 3338 return SDValue(); 3339 3340 // Avoid BUILD_VECTOR nodes that perform implicit truncation. 3341 // FIXME: This is valid and could be handled by truncating the APInts. 3342 if (V1->getValueType(0) != SVT || V2->getValueType(0) != SVT) 3343 return SDValue(); 3344 3345 // Fold one vector element. 3346 std::pair<APInt, bool> Folded = FoldValue(Opcode, V1->getAPIntValue(), 3347 V2->getAPIntValue()); 3348 if (!Folded.second) 3349 return SDValue(); 3350 Outputs.push_back(getConstant(Folded.first, DL, SVT)); 3351 } 3352 3353 assert(VT.getVectorNumElements() == Outputs.size() && 3354 "Vector size mismatch!"); 3355 3356 // We may have a vector type but a scalar result. Create a splat. 3357 Outputs.resize(VT.getVectorNumElements(), Outputs.back()); 3358 3359 // Build a big vector out of the scalar elements we generated. 3360 return getNode(ISD::BUILD_VECTOR, SDLoc(), VT, Outputs); 3361 } 3362 3363 SDValue SelectionDAG::FoldConstantVectorArithmetic(unsigned Opcode, SDLoc DL, 3364 EVT VT, 3365 ArrayRef<SDValue> Ops, 3366 const SDNodeFlags *Flags) { 3367 // If the opcode is a target-specific ISD node, there's nothing we can 3368 // do here and the operand rules may not line up with the below, so 3369 // bail early. 3370 if (Opcode >= ISD::BUILTIN_OP_END) 3371 return SDValue(); 3372 3373 // We can only fold vectors - maybe merge with FoldConstantArithmetic someday? 3374 if (!VT.isVector()) 3375 return SDValue(); 3376 3377 unsigned NumElts = VT.getVectorNumElements(); 3378 3379 auto IsScalarOrSameVectorSize = [&](const SDValue &Op) { 3380 return !Op.getValueType().isVector() || 3381 Op.getValueType().getVectorNumElements() == NumElts; 3382 }; 3383 3384 auto IsConstantBuildVectorOrUndef = [&](const SDValue &Op) { 3385 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op); 3386 return (Op.getOpcode() == ISD::UNDEF) || 3387 (Op.getOpcode() == ISD::CONDCODE) || (BV && BV->isConstant()); 3388 }; 3389 3390 // All operands must be vector types with the same number of elements as 3391 // the result type and must be either UNDEF or a build vector of constant 3392 // or UNDEF scalars. 3393 if (!std::all_of(Ops.begin(), Ops.end(), IsConstantBuildVectorOrUndef) || 3394 !std::all_of(Ops.begin(), Ops.end(), IsScalarOrSameVectorSize)) 3395 return SDValue(); 3396 3397 // If we are comparing vectors, then the result needs to be a i1 boolean 3398 // that is then sign-extended back to the legal result type. 3399 EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType()); 3400 3401 // Find legal integer scalar type for constant promotion and 3402 // ensure that its scalar size is at least as large as source. 3403 EVT LegalSVT = VT.getScalarType(); 3404 if (LegalSVT.isInteger()) { 3405 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT); 3406 if (LegalSVT.bitsLT(SVT)) 3407 return SDValue(); 3408 } 3409 3410 // Constant fold each scalar lane separately. 3411 SmallVector<SDValue, 4> ScalarResults; 3412 for (unsigned i = 0; i != NumElts; i++) { 3413 SmallVector<SDValue, 4> ScalarOps; 3414 for (SDValue Op : Ops) { 3415 EVT InSVT = Op.getValueType().getScalarType(); 3416 BuildVectorSDNode *InBV = dyn_cast<BuildVectorSDNode>(Op); 3417 if (!InBV) { 3418 // We've checked that this is UNDEF or a constant of some kind. 3419 if (Op.isUndef()) 3420 ScalarOps.push_back(getUNDEF(InSVT)); 3421 else 3422 ScalarOps.push_back(Op); 3423 continue; 3424 } 3425 3426 SDValue ScalarOp = InBV->getOperand(i); 3427 EVT ScalarVT = ScalarOp.getValueType(); 3428 3429 // Build vector (integer) scalar operands may need implicit 3430 // truncation - do this before constant folding. 3431 if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT)) 3432 ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp); 3433 3434 ScalarOps.push_back(ScalarOp); 3435 } 3436 3437 // Constant fold the scalar operands. 3438 SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps, Flags); 3439 3440 // Legalize the (integer) scalar constant if necessary. 3441 if (LegalSVT != SVT) 3442 ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult); 3443 3444 // Scalar folding only succeeded if the result is a constant or UNDEF. 3445 if (ScalarResult.getOpcode() != ISD::UNDEF && 3446 ScalarResult.getOpcode() != ISD::Constant && 3447 ScalarResult.getOpcode() != ISD::ConstantFP) 3448 return SDValue(); 3449 ScalarResults.push_back(ScalarResult); 3450 } 3451 3452 assert(ScalarResults.size() == NumElts && 3453 "Unexpected number of scalar results for BUILD_VECTOR"); 3454 return getNode(ISD::BUILD_VECTOR, DL, VT, ScalarResults); 3455 } 3456 3457 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, EVT VT, SDValue N1, 3458 SDValue N2, const SDNodeFlags *Flags) { 3459 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3460 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2); 3461 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 3462 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2); 3463 3464 // Canonicalize constant to RHS if commutative. 3465 if (isCommutativeBinOp(Opcode)) { 3466 if (N1C && !N2C) { 3467 std::swap(N1C, N2C); 3468 std::swap(N1, N2); 3469 } else if (N1CFP && !N2CFP) { 3470 std::swap(N1CFP, N2CFP); 3471 std::swap(N1, N2); 3472 } 3473 } 3474 3475 switch (Opcode) { 3476 default: break; 3477 case ISD::TokenFactor: 3478 assert(VT == MVT::Other && N1.getValueType() == MVT::Other && 3479 N2.getValueType() == MVT::Other && "Invalid token factor!"); 3480 // Fold trivial token factors. 3481 if (N1.getOpcode() == ISD::EntryToken) return N2; 3482 if (N2.getOpcode() == ISD::EntryToken) return N1; 3483 if (N1 == N2) return N1; 3484 break; 3485 case ISD::CONCAT_VECTORS: { 3486 // Attempt to fold CONCAT_VECTORS into BUILD_VECTOR or UNDEF. 3487 SDValue Ops[] = {N1, N2}; 3488 if (SDValue V = FoldCONCAT_VECTORS(DL, VT, Ops, *this)) 3489 return V; 3490 break; 3491 } 3492 case ISD::AND: 3493 assert(VT.isInteger() && "This operator does not apply to FP types!"); 3494 assert(N1.getValueType() == N2.getValueType() && 3495 N1.getValueType() == VT && "Binary operator types must match!"); 3496 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's 3497 // worth handling here. 3498 if (N2C && N2C->isNullValue()) 3499 return N2; 3500 if (N2C && N2C->isAllOnesValue()) // X & -1 -> X 3501 return N1; 3502 break; 3503 case ISD::OR: 3504 case ISD::XOR: 3505 case ISD::ADD: 3506 case ISD::SUB: 3507 assert(VT.isInteger() && "This operator does not apply to FP types!"); 3508 assert(N1.getValueType() == N2.getValueType() && 3509 N1.getValueType() == VT && "Binary operator types must match!"); 3510 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so 3511 // it's worth handling here. 3512 if (N2C && N2C->isNullValue()) 3513 return N1; 3514 break; 3515 case ISD::UDIV: 3516 case ISD::UREM: 3517 case ISD::MULHU: 3518 case ISD::MULHS: 3519 case ISD::MUL: 3520 case ISD::SDIV: 3521 case ISD::SREM: 3522 case ISD::SMIN: 3523 case ISD::SMAX: 3524 case ISD::UMIN: 3525 case ISD::UMAX: 3526 assert(VT.isInteger() && "This operator does not apply to FP types!"); 3527 assert(N1.getValueType() == N2.getValueType() && 3528 N1.getValueType() == VT && "Binary operator types must match!"); 3529 break; 3530 case ISD::FADD: 3531 case ISD::FSUB: 3532 case ISD::FMUL: 3533 case ISD::FDIV: 3534 case ISD::FREM: 3535 if (getTarget().Options.UnsafeFPMath) { 3536 if (Opcode == ISD::FADD) { 3537 // x+0 --> x 3538 if (N2CFP && N2CFP->getValueAPF().isZero()) 3539 return N1; 3540 } else if (Opcode == ISD::FSUB) { 3541 // x-0 --> x 3542 if (N2CFP && N2CFP->getValueAPF().isZero()) 3543 return N1; 3544 } else if (Opcode == ISD::FMUL) { 3545 // x*0 --> 0 3546 if (N2CFP && N2CFP->isZero()) 3547 return N2; 3548 // x*1 --> x 3549 if (N2CFP && N2CFP->isExactlyValue(1.0)) 3550 return N1; 3551 } 3552 } 3553 assert(VT.isFloatingPoint() && "This operator only applies to FP types!"); 3554 assert(N1.getValueType() == N2.getValueType() && 3555 N1.getValueType() == VT && "Binary operator types must match!"); 3556 break; 3557 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match. 3558 assert(N1.getValueType() == VT && 3559 N1.getValueType().isFloatingPoint() && 3560 N2.getValueType().isFloatingPoint() && 3561 "Invalid FCOPYSIGN!"); 3562 break; 3563 case ISD::SHL: 3564 case ISD::SRA: 3565 case ISD::SRL: 3566 case ISD::ROTL: 3567 case ISD::ROTR: 3568 assert(VT == N1.getValueType() && 3569 "Shift operators return type must be the same as their first arg"); 3570 assert(VT.isInteger() && N2.getValueType().isInteger() && 3571 "Shifts only work on integers"); 3572 assert((!VT.isVector() || VT == N2.getValueType()) && 3573 "Vector shift amounts must be in the same as their first arg"); 3574 // Verify that the shift amount VT is bit enough to hold valid shift 3575 // amounts. This catches things like trying to shift an i1024 value by an 3576 // i8, which is easy to fall into in generic code that uses 3577 // TLI.getShiftAmount(). 3578 assert(N2.getValueType().getSizeInBits() >= 3579 Log2_32_Ceil(N1.getValueType().getSizeInBits()) && 3580 "Invalid use of small shift amount with oversized value!"); 3581 3582 // Always fold shifts of i1 values so the code generator doesn't need to 3583 // handle them. Since we know the size of the shift has to be less than the 3584 // size of the value, the shift/rotate count is guaranteed to be zero. 3585 if (VT == MVT::i1) 3586 return N1; 3587 if (N2C && N2C->isNullValue()) 3588 return N1; 3589 break; 3590 case ISD::FP_ROUND_INREG: { 3591 EVT EVT = cast<VTSDNode>(N2)->getVT(); 3592 assert(VT == N1.getValueType() && "Not an inreg round!"); 3593 assert(VT.isFloatingPoint() && EVT.isFloatingPoint() && 3594 "Cannot FP_ROUND_INREG integer types"); 3595 assert(EVT.isVector() == VT.isVector() && 3596 "FP_ROUND_INREG type should be vector iff the operand " 3597 "type is vector!"); 3598 assert((!EVT.isVector() || 3599 EVT.getVectorNumElements() == VT.getVectorNumElements()) && 3600 "Vector element counts must match in FP_ROUND_INREG"); 3601 assert(EVT.bitsLE(VT) && "Not rounding down!"); 3602 (void)EVT; 3603 if (cast<VTSDNode>(N2)->getVT() == VT) return N1; // Not actually rounding. 3604 break; 3605 } 3606 case ISD::FP_ROUND: 3607 assert(VT.isFloatingPoint() && 3608 N1.getValueType().isFloatingPoint() && 3609 VT.bitsLE(N1.getValueType()) && 3610 N2C && "Invalid FP_ROUND!"); 3611 if (N1.getValueType() == VT) return N1; // noop conversion. 3612 break; 3613 case ISD::AssertSext: 3614 case ISD::AssertZext: { 3615 EVT EVT = cast<VTSDNode>(N2)->getVT(); 3616 assert(VT == N1.getValueType() && "Not an inreg extend!"); 3617 assert(VT.isInteger() && EVT.isInteger() && 3618 "Cannot *_EXTEND_INREG FP types"); 3619 assert(!EVT.isVector() && 3620 "AssertSExt/AssertZExt type should be the vector element type " 3621 "rather than the vector type!"); 3622 assert(EVT.bitsLE(VT) && "Not extending!"); 3623 if (VT == EVT) return N1; // noop assertion. 3624 break; 3625 } 3626 case ISD::SIGN_EXTEND_INREG: { 3627 EVT EVT = cast<VTSDNode>(N2)->getVT(); 3628 assert(VT == N1.getValueType() && "Not an inreg extend!"); 3629 assert(VT.isInteger() && EVT.isInteger() && 3630 "Cannot *_EXTEND_INREG FP types"); 3631 assert(EVT.isVector() == VT.isVector() && 3632 "SIGN_EXTEND_INREG type should be vector iff the operand " 3633 "type is vector!"); 3634 assert((!EVT.isVector() || 3635 EVT.getVectorNumElements() == VT.getVectorNumElements()) && 3636 "Vector element counts must match in SIGN_EXTEND_INREG"); 3637 assert(EVT.bitsLE(VT) && "Not extending!"); 3638 if (EVT == VT) return N1; // Not actually extending 3639 3640 auto SignExtendInReg = [&](APInt Val) { 3641 unsigned FromBits = EVT.getScalarType().getSizeInBits(); 3642 Val <<= Val.getBitWidth() - FromBits; 3643 Val = Val.ashr(Val.getBitWidth() - FromBits); 3644 return getConstant(Val, DL, VT.getScalarType()); 3645 }; 3646 3647 if (N1C) { 3648 APInt Val = N1C->getAPIntValue(); 3649 return SignExtendInReg(Val); 3650 } 3651 if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) { 3652 SmallVector<SDValue, 8> Ops; 3653 for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 3654 SDValue Op = N1.getOperand(i); 3655 if (Op.getOpcode() == ISD::UNDEF) { 3656 Ops.push_back(getUNDEF(VT.getScalarType())); 3657 continue; 3658 } 3659 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 3660 APInt Val = C->getAPIntValue(); 3661 Val = Val.zextOrTrunc(VT.getScalarSizeInBits()); 3662 Ops.push_back(SignExtendInReg(Val)); 3663 continue; 3664 } 3665 break; 3666 } 3667 if (Ops.size() == VT.getVectorNumElements()) 3668 return getNode(ISD::BUILD_VECTOR, DL, VT, Ops); 3669 } 3670 break; 3671 } 3672 case ISD::EXTRACT_VECTOR_ELT: 3673 // EXTRACT_VECTOR_ELT of an UNDEF is an UNDEF. 3674 if (N1.getOpcode() == ISD::UNDEF) 3675 return getUNDEF(VT); 3676 3677 // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF 3678 if (N2C && N2C->getZExtValue() >= N1.getValueType().getVectorNumElements()) 3679 return getUNDEF(VT); 3680 3681 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is 3682 // expanding copies of large vectors from registers. 3683 if (N2C && 3684 N1.getOpcode() == ISD::CONCAT_VECTORS && 3685 N1.getNumOperands() > 0) { 3686 unsigned Factor = 3687 N1.getOperand(0).getValueType().getVectorNumElements(); 3688 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, 3689 N1.getOperand(N2C->getZExtValue() / Factor), 3690 getConstant(N2C->getZExtValue() % Factor, DL, 3691 N2.getValueType())); 3692 } 3693 3694 // EXTRACT_VECTOR_ELT of BUILD_VECTOR is often formed while lowering is 3695 // expanding large vector constants. 3696 if (N2C && N1.getOpcode() == ISD::BUILD_VECTOR) { 3697 SDValue Elt = N1.getOperand(N2C->getZExtValue()); 3698 3699 if (VT != Elt.getValueType()) 3700 // If the vector element type is not legal, the BUILD_VECTOR operands 3701 // are promoted and implicitly truncated, and the result implicitly 3702 // extended. Make that explicit here. 3703 Elt = getAnyExtOrTrunc(Elt, DL, VT); 3704 3705 return Elt; 3706 } 3707 3708 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector 3709 // operations are lowered to scalars. 3710 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) { 3711 // If the indices are the same, return the inserted element else 3712 // if the indices are known different, extract the element from 3713 // the original vector. 3714 SDValue N1Op2 = N1.getOperand(2); 3715 ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2); 3716 3717 if (N1Op2C && N2C) { 3718 if (N1Op2C->getZExtValue() == N2C->getZExtValue()) { 3719 if (VT == N1.getOperand(1).getValueType()) 3720 return N1.getOperand(1); 3721 else 3722 return getSExtOrTrunc(N1.getOperand(1), DL, VT); 3723 } 3724 3725 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2); 3726 } 3727 } 3728 break; 3729 case ISD::EXTRACT_ELEMENT: 3730 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!"); 3731 assert(!N1.getValueType().isVector() && !VT.isVector() && 3732 (N1.getValueType().isInteger() == VT.isInteger()) && 3733 N1.getValueType() != VT && 3734 "Wrong types for EXTRACT_ELEMENT!"); 3735 3736 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding 3737 // 64-bit integers into 32-bit parts. Instead of building the extract of 3738 // the BUILD_PAIR, only to have legalize rip it apart, just do it now. 3739 if (N1.getOpcode() == ISD::BUILD_PAIR) 3740 return N1.getOperand(N2C->getZExtValue()); 3741 3742 // EXTRACT_ELEMENT of a constant int is also very common. 3743 if (N1C) { 3744 unsigned ElementSize = VT.getSizeInBits(); 3745 unsigned Shift = ElementSize * N2C->getZExtValue(); 3746 APInt ShiftedVal = N1C->getAPIntValue().lshr(Shift); 3747 return getConstant(ShiftedVal.trunc(ElementSize), DL, VT); 3748 } 3749 break; 3750 case ISD::EXTRACT_SUBVECTOR: 3751 if (VT.isSimple() && N1.getValueType().isSimple()) { 3752 assert(VT.isVector() && N1.getValueType().isVector() && 3753 "Extract subvector VTs must be a vectors!"); 3754 assert(VT.getVectorElementType() == 3755 N1.getValueType().getVectorElementType() && 3756 "Extract subvector VTs must have the same element type!"); 3757 assert(VT.getSimpleVT() <= N1.getSimpleValueType() && 3758 "Extract subvector must be from larger vector to smaller vector!"); 3759 3760 if (N2C) { 3761 assert((VT.getVectorNumElements() + N2C->getZExtValue() 3762 <= N1.getValueType().getVectorNumElements()) 3763 && "Extract subvector overflow!"); 3764 } 3765 3766 // Trivial extraction. 3767 if (VT.getSimpleVT() == N1.getSimpleValueType()) 3768 return N1; 3769 } 3770 break; 3771 } 3772 3773 // Perform trivial constant folding. 3774 if (SDValue SV = 3775 FoldConstantArithmetic(Opcode, DL, VT, N1.getNode(), N2.getNode())) 3776 return SV; 3777 3778 // Constant fold FP operations. 3779 bool HasFPExceptions = TLI->hasFloatingPointExceptions(); 3780 if (N1CFP) { 3781 if (N2CFP) { 3782 APFloat V1 = N1CFP->getValueAPF(), V2 = N2CFP->getValueAPF(); 3783 APFloat::opStatus s; 3784 switch (Opcode) { 3785 case ISD::FADD: 3786 s = V1.add(V2, APFloat::rmNearestTiesToEven); 3787 if (!HasFPExceptions || s != APFloat::opInvalidOp) 3788 return getConstantFP(V1, DL, VT); 3789 break; 3790 case ISD::FSUB: 3791 s = V1.subtract(V2, APFloat::rmNearestTiesToEven); 3792 if (!HasFPExceptions || s!=APFloat::opInvalidOp) 3793 return getConstantFP(V1, DL, VT); 3794 break; 3795 case ISD::FMUL: 3796 s = V1.multiply(V2, APFloat::rmNearestTiesToEven); 3797 if (!HasFPExceptions || s!=APFloat::opInvalidOp) 3798 return getConstantFP(V1, DL, VT); 3799 break; 3800 case ISD::FDIV: 3801 s = V1.divide(V2, APFloat::rmNearestTiesToEven); 3802 if (!HasFPExceptions || (s!=APFloat::opInvalidOp && 3803 s!=APFloat::opDivByZero)) { 3804 return getConstantFP(V1, DL, VT); 3805 } 3806 break; 3807 case ISD::FREM : 3808 s = V1.mod(V2); 3809 if (!HasFPExceptions || (s!=APFloat::opInvalidOp && 3810 s!=APFloat::opDivByZero)) { 3811 return getConstantFP(V1, DL, VT); 3812 } 3813 break; 3814 case ISD::FCOPYSIGN: 3815 V1.copySign(V2); 3816 return getConstantFP(V1, DL, VT); 3817 default: break; 3818 } 3819 } 3820 3821 if (Opcode == ISD::FP_ROUND) { 3822 APFloat V = N1CFP->getValueAPF(); // make copy 3823 bool ignored; 3824 // This can return overflow, underflow, or inexact; we don't care. 3825 // FIXME need to be more flexible about rounding mode. 3826 (void)V.convert(EVTToAPFloatSemantics(VT), 3827 APFloat::rmNearestTiesToEven, &ignored); 3828 return getConstantFP(V, DL, VT); 3829 } 3830 } 3831 3832 // Canonicalize an UNDEF to the RHS, even over a constant. 3833 if (N1.getOpcode() == ISD::UNDEF) { 3834 if (isCommutativeBinOp(Opcode)) { 3835 std::swap(N1, N2); 3836 } else { 3837 switch (Opcode) { 3838 case ISD::FP_ROUND_INREG: 3839 case ISD::SIGN_EXTEND_INREG: 3840 case ISD::SUB: 3841 case ISD::FSUB: 3842 case ISD::FDIV: 3843 case ISD::FREM: 3844 case ISD::SRA: 3845 return N1; // fold op(undef, arg2) -> undef 3846 case ISD::UDIV: 3847 case ISD::SDIV: 3848 case ISD::UREM: 3849 case ISD::SREM: 3850 case ISD::SRL: 3851 case ISD::SHL: 3852 if (!VT.isVector()) 3853 return getConstant(0, DL, VT); // fold op(undef, arg2) -> 0 3854 // For vectors, we can't easily build an all zero vector, just return 3855 // the LHS. 3856 return N2; 3857 } 3858 } 3859 } 3860 3861 // Fold a bunch of operators when the RHS is undef. 3862 if (N2.getOpcode() == ISD::UNDEF) { 3863 switch (Opcode) { 3864 case ISD::XOR: 3865 if (N1.getOpcode() == ISD::UNDEF) 3866 // Handle undef ^ undef -> 0 special case. This is a common 3867 // idiom (misuse). 3868 return getConstant(0, DL, VT); 3869 // fallthrough 3870 case ISD::ADD: 3871 case ISD::ADDC: 3872 case ISD::ADDE: 3873 case ISD::SUB: 3874 case ISD::UDIV: 3875 case ISD::SDIV: 3876 case ISD::UREM: 3877 case ISD::SREM: 3878 return N2; // fold op(arg1, undef) -> undef 3879 case ISD::FADD: 3880 case ISD::FSUB: 3881 case ISD::FMUL: 3882 case ISD::FDIV: 3883 case ISD::FREM: 3884 if (getTarget().Options.UnsafeFPMath) 3885 return N2; 3886 break; 3887 case ISD::MUL: 3888 case ISD::AND: 3889 case ISD::SRL: 3890 case ISD::SHL: 3891 if (!VT.isVector()) 3892 return getConstant(0, DL, VT); // fold op(arg1, undef) -> 0 3893 // For vectors, we can't easily build an all zero vector, just return 3894 // the LHS. 3895 return N1; 3896 case ISD::OR: 3897 if (!VT.isVector()) 3898 return getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT); 3899 // For vectors, we can't easily build an all one vector, just return 3900 // the LHS. 3901 return N1; 3902 case ISD::SRA: 3903 return N1; 3904 } 3905 } 3906 3907 // Memoize this node if possible. 3908 BinarySDNode *N; 3909 SDVTList VTs = getVTList(VT); 3910 if (VT != MVT::Glue) { 3911 SDValue Ops[] = {N1, N2}; 3912 FoldingSetNodeID ID; 3913 AddNodeIDNode(ID, Opcode, VTs, Ops); 3914 void *IP = nullptr; 3915 if (SDNode *E = FindNodeOrInsertPos(ID, DL.getDebugLoc(), IP)) { 3916 if (Flags) 3917 E->intersectFlagsWith(Flags); 3918 return SDValue(E, 0); 3919 } 3920 3921 N = GetBinarySDNode(Opcode, DL, VTs, N1, N2, Flags); 3922 3923 CSEMap.InsertNode(N, IP); 3924 } else { 3925 N = GetBinarySDNode(Opcode, DL, VTs, N1, N2, Flags); 3926 } 3927 3928 InsertNode(N); 3929 return SDValue(N, 0); 3930 } 3931 3932 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, EVT VT, 3933 SDValue N1, SDValue N2, SDValue N3) { 3934 // Perform various simplifications. 3935 switch (Opcode) { 3936 case ISD::FMA: { 3937 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 3938 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2); 3939 ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3); 3940 if (N1CFP && N2CFP && N3CFP) { 3941 APFloat V1 = N1CFP->getValueAPF(); 3942 const APFloat &V2 = N2CFP->getValueAPF(); 3943 const APFloat &V3 = N3CFP->getValueAPF(); 3944 APFloat::opStatus s = 3945 V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven); 3946 if (!TLI->hasFloatingPointExceptions() || s != APFloat::opInvalidOp) 3947 return getConstantFP(V1, DL, VT); 3948 } 3949 break; 3950 } 3951 case ISD::CONCAT_VECTORS: { 3952 // Attempt to fold CONCAT_VECTORS into BUILD_VECTOR or UNDEF. 3953 SDValue Ops[] = {N1, N2, N3}; 3954 if (SDValue V = FoldCONCAT_VECTORS(DL, VT, Ops, *this)) 3955 return V; 3956 break; 3957 } 3958 case ISD::SETCC: { 3959 // Use FoldSetCC to simplify SETCC's. 3960 if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL)) 3961 return V; 3962 // Vector constant folding. 3963 SDValue Ops[] = {N1, N2, N3}; 3964 if (SDValue V = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops)) 3965 return V; 3966 break; 3967 } 3968 case ISD::SELECT: 3969 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) { 3970 if (N1C->getZExtValue()) 3971 return N2; // select true, X, Y -> X 3972 return N3; // select false, X, Y -> Y 3973 } 3974 3975 if (N2 == N3) return N2; // select C, X, X -> X 3976 break; 3977 case ISD::VECTOR_SHUFFLE: 3978 llvm_unreachable("should use getVectorShuffle constructor!"); 3979 case ISD::INSERT_SUBVECTOR: { 3980 SDValue Index = N3; 3981 if (VT.isSimple() && N1.getValueType().isSimple() 3982 && N2.getValueType().isSimple()) { 3983 assert(VT.isVector() && N1.getValueType().isVector() && 3984 N2.getValueType().isVector() && 3985 "Insert subvector VTs must be a vectors"); 3986 assert(VT == N1.getValueType() && 3987 "Dest and insert subvector source types must match!"); 3988 assert(N2.getSimpleValueType() <= N1.getSimpleValueType() && 3989 "Insert subvector must be from smaller vector to larger vector!"); 3990 if (isa<ConstantSDNode>(Index)) { 3991 assert((N2.getValueType().getVectorNumElements() + 3992 cast<ConstantSDNode>(Index)->getZExtValue() 3993 <= VT.getVectorNumElements()) 3994 && "Insert subvector overflow!"); 3995 } 3996 3997 // Trivial insertion. 3998 if (VT.getSimpleVT() == N2.getSimpleValueType()) 3999 return N2; 4000 } 4001 break; 4002 } 4003 case ISD::BITCAST: 4004 // Fold bit_convert nodes from a type to themselves. 4005 if (N1.getValueType() == VT) 4006 return N1; 4007 break; 4008 } 4009 4010 // Memoize node if it doesn't produce a flag. 4011 SDNode *N; 4012 SDVTList VTs = getVTList(VT); 4013 if (VT != MVT::Glue) { 4014 SDValue Ops[] = { N1, N2, N3 }; 4015 FoldingSetNodeID ID; 4016 AddNodeIDNode(ID, Opcode, VTs, Ops); 4017 void *IP = nullptr; 4018 if (SDNode *E = FindNodeOrInsertPos(ID, DL.getDebugLoc(), IP)) 4019 return SDValue(E, 0); 4020 4021 N = new (NodeAllocator) TernarySDNode(Opcode, DL.getIROrder(), 4022 DL.getDebugLoc(), VTs, N1, N2, N3); 4023 CSEMap.InsertNode(N, IP); 4024 } else { 4025 N = new (NodeAllocator) TernarySDNode(Opcode, DL.getIROrder(), 4026 DL.getDebugLoc(), VTs, N1, N2, N3); 4027 } 4028 4029 InsertNode(N); 4030 return SDValue(N, 0); 4031 } 4032 4033 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, EVT VT, 4034 SDValue N1, SDValue N2, SDValue N3, 4035 SDValue N4) { 4036 SDValue Ops[] = { N1, N2, N3, N4 }; 4037 return getNode(Opcode, DL, VT, Ops); 4038 } 4039 4040 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, EVT VT, 4041 SDValue N1, SDValue N2, SDValue N3, 4042 SDValue N4, SDValue N5) { 4043 SDValue Ops[] = { N1, N2, N3, N4, N5 }; 4044 return getNode(Opcode, DL, VT, Ops); 4045 } 4046 4047 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all 4048 /// the incoming stack arguments to be loaded from the stack. 4049 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) { 4050 SmallVector<SDValue, 8> ArgChains; 4051 4052 // Include the original chain at the beginning of the list. When this is 4053 // used by target LowerCall hooks, this helps legalize find the 4054 // CALLSEQ_BEGIN node. 4055 ArgChains.push_back(Chain); 4056 4057 // Add a chain value for each stack argument. 4058 for (SDNode::use_iterator U = getEntryNode().getNode()->use_begin(), 4059 UE = getEntryNode().getNode()->use_end(); U != UE; ++U) 4060 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U)) 4061 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr())) 4062 if (FI->getIndex() < 0) 4063 ArgChains.push_back(SDValue(L, 1)); 4064 4065 // Build a tokenfactor for all the chains. 4066 return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains); 4067 } 4068 4069 /// getMemsetValue - Vectorized representation of the memset value 4070 /// operand. 4071 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG, 4072 SDLoc dl) { 4073 assert(Value.getOpcode() != ISD::UNDEF); 4074 4075 unsigned NumBits = VT.getScalarType().getSizeInBits(); 4076 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) { 4077 assert(C->getAPIntValue().getBitWidth() == 8); 4078 APInt Val = APInt::getSplat(NumBits, C->getAPIntValue()); 4079 if (VT.isInteger()) 4080 return DAG.getConstant(Val, dl, VT); 4081 return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl, 4082 VT); 4083 } 4084 4085 assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?"); 4086 EVT IntVT = VT.getScalarType(); 4087 if (!IntVT.isInteger()) 4088 IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits()); 4089 4090 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value); 4091 if (NumBits > 8) { 4092 // Use a multiplication with 0x010101... to extend the input to the 4093 // required length. 4094 APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01)); 4095 Value = DAG.getNode(ISD::MUL, dl, IntVT, Value, 4096 DAG.getConstant(Magic, dl, IntVT)); 4097 } 4098 4099 if (VT != Value.getValueType() && !VT.isInteger()) 4100 Value = DAG.getNode(ISD::BITCAST, dl, VT.getScalarType(), Value); 4101 if (VT != Value.getValueType()) { 4102 assert(VT.getVectorElementType() == Value.getValueType() && 4103 "value type should be one vector element here"); 4104 SmallVector<SDValue, 8> BVOps(VT.getVectorNumElements(), Value); 4105 Value = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, BVOps); 4106 } 4107 4108 return Value; 4109 } 4110 4111 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only 4112 /// used when a memcpy is turned into a memset when the source is a constant 4113 /// string ptr. 4114 static SDValue getMemsetStringVal(EVT VT, SDLoc dl, SelectionDAG &DAG, 4115 const TargetLowering &TLI, StringRef Str) { 4116 // Handle vector with all elements zero. 4117 if (Str.empty()) { 4118 if (VT.isInteger()) 4119 return DAG.getConstant(0, dl, VT); 4120 else if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128) 4121 return DAG.getConstantFP(0.0, dl, VT); 4122 else if (VT.isVector()) { 4123 unsigned NumElts = VT.getVectorNumElements(); 4124 MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64; 4125 return DAG.getNode(ISD::BITCAST, dl, VT, 4126 DAG.getConstant(0, dl, 4127 EVT::getVectorVT(*DAG.getContext(), 4128 EltVT, NumElts))); 4129 } else 4130 llvm_unreachable("Expected type!"); 4131 } 4132 4133 assert(!VT.isVector() && "Can't handle vector type here!"); 4134 unsigned NumVTBits = VT.getSizeInBits(); 4135 unsigned NumVTBytes = NumVTBits / 8; 4136 unsigned NumBytes = std::min(NumVTBytes, unsigned(Str.size())); 4137 4138 APInt Val(NumVTBits, 0); 4139 if (DAG.getDataLayout().isLittleEndian()) { 4140 for (unsigned i = 0; i != NumBytes; ++i) 4141 Val |= (uint64_t)(unsigned char)Str[i] << i*8; 4142 } else { 4143 for (unsigned i = 0; i != NumBytes; ++i) 4144 Val |= (uint64_t)(unsigned char)Str[i] << (NumVTBytes-i-1)*8; 4145 } 4146 4147 // If the "cost" of materializing the integer immediate is less than the cost 4148 // of a load, then it is cost effective to turn the load into the immediate. 4149 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 4150 if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty)) 4151 return DAG.getConstant(Val, dl, VT); 4152 return SDValue(nullptr, 0); 4153 } 4154 4155 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, unsigned Offset, 4156 SDLoc DL) { 4157 EVT VT = Base.getValueType(); 4158 return getNode(ISD::ADD, DL, VT, Base, getConstant(Offset, DL, VT)); 4159 } 4160 4161 /// isMemSrcFromString - Returns true if memcpy source is a string constant. 4162 /// 4163 static bool isMemSrcFromString(SDValue Src, StringRef &Str) { 4164 uint64_t SrcDelta = 0; 4165 GlobalAddressSDNode *G = nullptr; 4166 if (Src.getOpcode() == ISD::GlobalAddress) 4167 G = cast<GlobalAddressSDNode>(Src); 4168 else if (Src.getOpcode() == ISD::ADD && 4169 Src.getOperand(0).getOpcode() == ISD::GlobalAddress && 4170 Src.getOperand(1).getOpcode() == ISD::Constant) { 4171 G = cast<GlobalAddressSDNode>(Src.getOperand(0)); 4172 SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue(); 4173 } 4174 if (!G) 4175 return false; 4176 4177 return getConstantStringInfo(G->getGlobal(), Str, 4178 SrcDelta + G->getOffset(), false); 4179 } 4180 4181 /// Determines the optimal series of memory ops to replace the memset / memcpy. 4182 /// Return true if the number of memory ops is below the threshold (Limit). 4183 /// It returns the types of the sequence of memory ops to perform 4184 /// memset / memcpy by reference. 4185 static bool FindOptimalMemOpLowering(std::vector<EVT> &MemOps, 4186 unsigned Limit, uint64_t Size, 4187 unsigned DstAlign, unsigned SrcAlign, 4188 bool IsMemset, 4189 bool ZeroMemset, 4190 bool MemcpyStrSrc, 4191 bool AllowOverlap, 4192 unsigned DstAS, unsigned SrcAS, 4193 SelectionDAG &DAG, 4194 const TargetLowering &TLI) { 4195 assert((SrcAlign == 0 || SrcAlign >= DstAlign) && 4196 "Expecting memcpy / memset source to meet alignment requirement!"); 4197 // If 'SrcAlign' is zero, that means the memory operation does not need to 4198 // load the value, i.e. memset or memcpy from constant string. Otherwise, 4199 // it's the inferred alignment of the source. 'DstAlign', on the other hand, 4200 // is the specified alignment of the memory operation. If it is zero, that 4201 // means it's possible to change the alignment of the destination. 4202 // 'MemcpyStrSrc' indicates whether the memcpy source is constant so it does 4203 // not need to be loaded. 4204 EVT VT = TLI.getOptimalMemOpType(Size, DstAlign, SrcAlign, 4205 IsMemset, ZeroMemset, MemcpyStrSrc, 4206 DAG.getMachineFunction()); 4207 4208 if (VT == MVT::Other) { 4209 if (DstAlign >= DAG.getDataLayout().getPointerPrefAlignment(DstAS) || 4210 TLI.allowsMisalignedMemoryAccesses(VT, DstAS, DstAlign)) { 4211 VT = TLI.getPointerTy(DAG.getDataLayout(), DstAS); 4212 } else { 4213 switch (DstAlign & 7) { 4214 case 0: VT = MVT::i64; break; 4215 case 4: VT = MVT::i32; break; 4216 case 2: VT = MVT::i16; break; 4217 default: VT = MVT::i8; break; 4218 } 4219 } 4220 4221 MVT LVT = MVT::i64; 4222 while (!TLI.isTypeLegal(LVT)) 4223 LVT = (MVT::SimpleValueType)(LVT.SimpleTy - 1); 4224 assert(LVT.isInteger()); 4225 4226 if (VT.bitsGT(LVT)) 4227 VT = LVT; 4228 } 4229 4230 unsigned NumMemOps = 0; 4231 while (Size != 0) { 4232 unsigned VTSize = VT.getSizeInBits() / 8; 4233 while (VTSize > Size) { 4234 // For now, only use non-vector load / store's for the left-over pieces. 4235 EVT NewVT = VT; 4236 unsigned NewVTSize; 4237 4238 bool Found = false; 4239 if (VT.isVector() || VT.isFloatingPoint()) { 4240 NewVT = (VT.getSizeInBits() > 64) ? MVT::i64 : MVT::i32; 4241 if (TLI.isOperationLegalOrCustom(ISD::STORE, NewVT) && 4242 TLI.isSafeMemOpType(NewVT.getSimpleVT())) 4243 Found = true; 4244 else if (NewVT == MVT::i64 && 4245 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::f64) && 4246 TLI.isSafeMemOpType(MVT::f64)) { 4247 // i64 is usually not legal on 32-bit targets, but f64 may be. 4248 NewVT = MVT::f64; 4249 Found = true; 4250 } 4251 } 4252 4253 if (!Found) { 4254 do { 4255 NewVT = (MVT::SimpleValueType)(NewVT.getSimpleVT().SimpleTy - 1); 4256 if (NewVT == MVT::i8) 4257 break; 4258 } while (!TLI.isSafeMemOpType(NewVT.getSimpleVT())); 4259 } 4260 NewVTSize = NewVT.getSizeInBits() / 8; 4261 4262 // If the new VT cannot cover all of the remaining bits, then consider 4263 // issuing a (or a pair of) unaligned and overlapping load / store. 4264 // FIXME: Only does this for 64-bit or more since we don't have proper 4265 // cost model for unaligned load / store. 4266 bool Fast; 4267 if (NumMemOps && AllowOverlap && 4268 VTSize >= 8 && NewVTSize < Size && 4269 TLI.allowsMisalignedMemoryAccesses(VT, DstAS, DstAlign, &Fast) && Fast) 4270 VTSize = Size; 4271 else { 4272 VT = NewVT; 4273 VTSize = NewVTSize; 4274 } 4275 } 4276 4277 if (++NumMemOps > Limit) 4278 return false; 4279 4280 MemOps.push_back(VT); 4281 Size -= VTSize; 4282 } 4283 4284 return true; 4285 } 4286 4287 static bool shouldLowerMemFuncForSize(const MachineFunction &MF) { 4288 // On Darwin, -Os means optimize for size without hurting performance, so 4289 // only really optimize for size when -Oz (MinSize) is used. 4290 if (MF.getTarget().getTargetTriple().isOSDarwin()) 4291 return MF.getFunction()->optForMinSize(); 4292 return MF.getFunction()->optForSize(); 4293 } 4294 4295 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, SDLoc dl, 4296 SDValue Chain, SDValue Dst, 4297 SDValue Src, uint64_t Size, 4298 unsigned Align, bool isVol, 4299 bool AlwaysInline, 4300 MachinePointerInfo DstPtrInfo, 4301 MachinePointerInfo SrcPtrInfo) { 4302 // Turn a memcpy of undef to nop. 4303 if (Src.getOpcode() == ISD::UNDEF) 4304 return Chain; 4305 4306 // Expand memcpy to a series of load and store ops if the size operand falls 4307 // below a certain threshold. 4308 // TODO: In the AlwaysInline case, if the size is big then generate a loop 4309 // rather than maybe a humongous number of loads and stores. 4310 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4311 std::vector<EVT> MemOps; 4312 bool DstAlignCanChange = false; 4313 MachineFunction &MF = DAG.getMachineFunction(); 4314 MachineFrameInfo *MFI = MF.getFrameInfo(); 4315 bool OptSize = shouldLowerMemFuncForSize(MF); 4316 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 4317 if (FI && !MFI->isFixedObjectIndex(FI->getIndex())) 4318 DstAlignCanChange = true; 4319 unsigned SrcAlign = DAG.InferPtrAlignment(Src); 4320 if (Align > SrcAlign) 4321 SrcAlign = Align; 4322 StringRef Str; 4323 bool CopyFromStr = isMemSrcFromString(Src, Str); 4324 bool isZeroStr = CopyFromStr && Str.empty(); 4325 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize); 4326 4327 if (!FindOptimalMemOpLowering(MemOps, Limit, Size, 4328 (DstAlignCanChange ? 0 : Align), 4329 (isZeroStr ? 0 : SrcAlign), 4330 false, false, CopyFromStr, true, 4331 DstPtrInfo.getAddrSpace(), 4332 SrcPtrInfo.getAddrSpace(), 4333 DAG, TLI)) 4334 return SDValue(); 4335 4336 if (DstAlignCanChange) { 4337 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext()); 4338 unsigned NewAlign = (unsigned)DAG.getDataLayout().getABITypeAlignment(Ty); 4339 4340 // Don't promote to an alignment that would require dynamic stack 4341 // realignment. 4342 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); 4343 if (!TRI->needsStackRealignment(MF)) 4344 while (NewAlign > Align && 4345 DAG.getDataLayout().exceedsNaturalStackAlignment(NewAlign)) 4346 NewAlign /= 2; 4347 4348 if (NewAlign > Align) { 4349 // Give the stack frame object a larger alignment if needed. 4350 if (MFI->getObjectAlignment(FI->getIndex()) < NewAlign) 4351 MFI->setObjectAlignment(FI->getIndex(), NewAlign); 4352 Align = NewAlign; 4353 } 4354 } 4355 4356 SmallVector<SDValue, 8> OutChains; 4357 unsigned NumMemOps = MemOps.size(); 4358 uint64_t SrcOff = 0, DstOff = 0; 4359 for (unsigned i = 0; i != NumMemOps; ++i) { 4360 EVT VT = MemOps[i]; 4361 unsigned VTSize = VT.getSizeInBits() / 8; 4362 SDValue Value, Store; 4363 4364 if (VTSize > Size) { 4365 // Issuing an unaligned load / store pair that overlaps with the previous 4366 // pair. Adjust the offset accordingly. 4367 assert(i == NumMemOps-1 && i != 0); 4368 SrcOff -= VTSize - Size; 4369 DstOff -= VTSize - Size; 4370 } 4371 4372 if (CopyFromStr && 4373 (isZeroStr || (VT.isInteger() && !VT.isVector()))) { 4374 // It's unlikely a store of a vector immediate can be done in a single 4375 // instruction. It would require a load from a constantpool first. 4376 // We only handle zero vectors here. 4377 // FIXME: Handle other cases where store of vector immediate is done in 4378 // a single instruction. 4379 Value = getMemsetStringVal(VT, dl, DAG, TLI, Str.substr(SrcOff)); 4380 if (Value.getNode()) 4381 Store = DAG.getStore(Chain, dl, Value, 4382 DAG.getMemBasePlusOffset(Dst, DstOff, dl), 4383 DstPtrInfo.getWithOffset(DstOff), isVol, 4384 false, Align); 4385 } 4386 4387 if (!Store.getNode()) { 4388 // The type might not be legal for the target. This should only happen 4389 // if the type is smaller than a legal type, as on PPC, so the right 4390 // thing to do is generate a LoadExt/StoreTrunc pair. These simplify 4391 // to Load/Store if NVT==VT. 4392 // FIXME does the case above also need this? 4393 EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT); 4394 assert(NVT.bitsGE(VT)); 4395 Value = DAG.getExtLoad(ISD::EXTLOAD, dl, NVT, Chain, 4396 DAG.getMemBasePlusOffset(Src, SrcOff, dl), 4397 SrcPtrInfo.getWithOffset(SrcOff), VT, isVol, false, 4398 false, MinAlign(SrcAlign, SrcOff)); 4399 Store = DAG.getTruncStore(Chain, dl, Value, 4400 DAG.getMemBasePlusOffset(Dst, DstOff, dl), 4401 DstPtrInfo.getWithOffset(DstOff), VT, isVol, 4402 false, Align); 4403 } 4404 OutChains.push_back(Store); 4405 SrcOff += VTSize; 4406 DstOff += VTSize; 4407 Size -= VTSize; 4408 } 4409 4410 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 4411 } 4412 4413 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, SDLoc dl, 4414 SDValue Chain, SDValue Dst, 4415 SDValue Src, uint64_t Size, 4416 unsigned Align, bool isVol, 4417 bool AlwaysInline, 4418 MachinePointerInfo DstPtrInfo, 4419 MachinePointerInfo SrcPtrInfo) { 4420 // Turn a memmove of undef to nop. 4421 if (Src.getOpcode() == ISD::UNDEF) 4422 return Chain; 4423 4424 // Expand memmove to a series of load and store ops if the size operand falls 4425 // below a certain threshold. 4426 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4427 std::vector<EVT> MemOps; 4428 bool DstAlignCanChange = false; 4429 MachineFunction &MF = DAG.getMachineFunction(); 4430 MachineFrameInfo *MFI = MF.getFrameInfo(); 4431 bool OptSize = shouldLowerMemFuncForSize(MF); 4432 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 4433 if (FI && !MFI->isFixedObjectIndex(FI->getIndex())) 4434 DstAlignCanChange = true; 4435 unsigned SrcAlign = DAG.InferPtrAlignment(Src); 4436 if (Align > SrcAlign) 4437 SrcAlign = Align; 4438 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize); 4439 4440 if (!FindOptimalMemOpLowering(MemOps, Limit, Size, 4441 (DstAlignCanChange ? 0 : Align), SrcAlign, 4442 false, false, false, false, 4443 DstPtrInfo.getAddrSpace(), 4444 SrcPtrInfo.getAddrSpace(), 4445 DAG, TLI)) 4446 return SDValue(); 4447 4448 if (DstAlignCanChange) { 4449 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext()); 4450 unsigned NewAlign = (unsigned)DAG.getDataLayout().getABITypeAlignment(Ty); 4451 if (NewAlign > Align) { 4452 // Give the stack frame object a larger alignment if needed. 4453 if (MFI->getObjectAlignment(FI->getIndex()) < NewAlign) 4454 MFI->setObjectAlignment(FI->getIndex(), NewAlign); 4455 Align = NewAlign; 4456 } 4457 } 4458 4459 uint64_t SrcOff = 0, DstOff = 0; 4460 SmallVector<SDValue, 8> LoadValues; 4461 SmallVector<SDValue, 8> LoadChains; 4462 SmallVector<SDValue, 8> OutChains; 4463 unsigned NumMemOps = MemOps.size(); 4464 for (unsigned i = 0; i < NumMemOps; i++) { 4465 EVT VT = MemOps[i]; 4466 unsigned VTSize = VT.getSizeInBits() / 8; 4467 SDValue Value; 4468 4469 Value = DAG.getLoad(VT, dl, Chain, 4470 DAG.getMemBasePlusOffset(Src, SrcOff, dl), 4471 SrcPtrInfo.getWithOffset(SrcOff), isVol, 4472 false, false, SrcAlign); 4473 LoadValues.push_back(Value); 4474 LoadChains.push_back(Value.getValue(1)); 4475 SrcOff += VTSize; 4476 } 4477 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 4478 OutChains.clear(); 4479 for (unsigned i = 0; i < NumMemOps; i++) { 4480 EVT VT = MemOps[i]; 4481 unsigned VTSize = VT.getSizeInBits() / 8; 4482 SDValue Store; 4483 4484 Store = DAG.getStore(Chain, dl, LoadValues[i], 4485 DAG.getMemBasePlusOffset(Dst, DstOff, dl), 4486 DstPtrInfo.getWithOffset(DstOff), isVol, false, Align); 4487 OutChains.push_back(Store); 4488 DstOff += VTSize; 4489 } 4490 4491 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 4492 } 4493 4494 /// \brief Lower the call to 'memset' intrinsic function into a series of store 4495 /// operations. 4496 /// 4497 /// \param DAG Selection DAG where lowered code is placed. 4498 /// \param dl Link to corresponding IR location. 4499 /// \param Chain Control flow dependency. 4500 /// \param Dst Pointer to destination memory location. 4501 /// \param Src Value of byte to write into the memory. 4502 /// \param Size Number of bytes to write. 4503 /// \param Align Alignment of the destination in bytes. 4504 /// \param isVol True if destination is volatile. 4505 /// \param DstPtrInfo IR information on the memory pointer. 4506 /// \returns New head in the control flow, if lowering was successful, empty 4507 /// SDValue otherwise. 4508 /// 4509 /// The function tries to replace 'llvm.memset' intrinsic with several store 4510 /// operations and value calculation code. This is usually profitable for small 4511 /// memory size. 4512 static SDValue getMemsetStores(SelectionDAG &DAG, SDLoc dl, 4513 SDValue Chain, SDValue Dst, 4514 SDValue Src, uint64_t Size, 4515 unsigned Align, bool isVol, 4516 MachinePointerInfo DstPtrInfo) { 4517 // Turn a memset of undef to nop. 4518 if (Src.getOpcode() == ISD::UNDEF) 4519 return Chain; 4520 4521 // Expand memset to a series of load/store ops if the size operand 4522 // falls below a certain threshold. 4523 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4524 std::vector<EVT> MemOps; 4525 bool DstAlignCanChange = false; 4526 MachineFunction &MF = DAG.getMachineFunction(); 4527 MachineFrameInfo *MFI = MF.getFrameInfo(); 4528 bool OptSize = shouldLowerMemFuncForSize(MF); 4529 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 4530 if (FI && !MFI->isFixedObjectIndex(FI->getIndex())) 4531 DstAlignCanChange = true; 4532 bool IsZeroVal = 4533 isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isNullValue(); 4534 if (!FindOptimalMemOpLowering(MemOps, TLI.getMaxStoresPerMemset(OptSize), 4535 Size, (DstAlignCanChange ? 0 : Align), 0, 4536 true, IsZeroVal, false, true, 4537 DstPtrInfo.getAddrSpace(), ~0u, 4538 DAG, TLI)) 4539 return SDValue(); 4540 4541 if (DstAlignCanChange) { 4542 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext()); 4543 unsigned NewAlign = (unsigned)DAG.getDataLayout().getABITypeAlignment(Ty); 4544 if (NewAlign > Align) { 4545 // Give the stack frame object a larger alignment if needed. 4546 if (MFI->getObjectAlignment(FI->getIndex()) < NewAlign) 4547 MFI->setObjectAlignment(FI->getIndex(), NewAlign); 4548 Align = NewAlign; 4549 } 4550 } 4551 4552 SmallVector<SDValue, 8> OutChains; 4553 uint64_t DstOff = 0; 4554 unsigned NumMemOps = MemOps.size(); 4555 4556 // Find the largest store and generate the bit pattern for it. 4557 EVT LargestVT = MemOps[0]; 4558 for (unsigned i = 1; i < NumMemOps; i++) 4559 if (MemOps[i].bitsGT(LargestVT)) 4560 LargestVT = MemOps[i]; 4561 SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl); 4562 4563 for (unsigned i = 0; i < NumMemOps; i++) { 4564 EVT VT = MemOps[i]; 4565 unsigned VTSize = VT.getSizeInBits() / 8; 4566 if (VTSize > Size) { 4567 // Issuing an unaligned load / store pair that overlaps with the previous 4568 // pair. Adjust the offset accordingly. 4569 assert(i == NumMemOps-1 && i != 0); 4570 DstOff -= VTSize - Size; 4571 } 4572 4573 // If this store is smaller than the largest store see whether we can get 4574 // the smaller value for free with a truncate. 4575 SDValue Value = MemSetValue; 4576 if (VT.bitsLT(LargestVT)) { 4577 if (!LargestVT.isVector() && !VT.isVector() && 4578 TLI.isTruncateFree(LargestVT, VT)) 4579 Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue); 4580 else 4581 Value = getMemsetValue(Src, VT, DAG, dl); 4582 } 4583 assert(Value.getValueType() == VT && "Value with wrong type."); 4584 SDValue Store = DAG.getStore(Chain, dl, Value, 4585 DAG.getMemBasePlusOffset(Dst, DstOff, dl), 4586 DstPtrInfo.getWithOffset(DstOff), 4587 isVol, false, Align); 4588 OutChains.push_back(Store); 4589 DstOff += VT.getSizeInBits() / 8; 4590 Size -= VTSize; 4591 } 4592 4593 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 4594 } 4595 4596 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI, 4597 unsigned AS) { 4598 // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all 4599 // pointer operands can be losslessly bitcasted to pointers of address space 0 4600 if (AS != 0 && !TLI->isNoopAddrSpaceCast(AS, 0)) { 4601 report_fatal_error("cannot lower memory intrinsic in address space " + 4602 Twine(AS)); 4603 } 4604 } 4605 4606 SDValue SelectionDAG::getMemcpy(SDValue Chain, SDLoc dl, SDValue Dst, 4607 SDValue Src, SDValue Size, 4608 unsigned Align, bool isVol, bool AlwaysInline, 4609 bool isTailCall, MachinePointerInfo DstPtrInfo, 4610 MachinePointerInfo SrcPtrInfo) { 4611 assert(Align && "The SDAG layer expects explicit alignment and reserves 0"); 4612 4613 // Check to see if we should lower the memcpy to loads and stores first. 4614 // For cases within the target-specified limits, this is the best choice. 4615 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 4616 if (ConstantSize) { 4617 // Memcpy with size zero? Just return the original chain. 4618 if (ConstantSize->isNullValue()) 4619 return Chain; 4620 4621 SDValue Result = getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src, 4622 ConstantSize->getZExtValue(),Align, 4623 isVol, false, DstPtrInfo, SrcPtrInfo); 4624 if (Result.getNode()) 4625 return Result; 4626 } 4627 4628 // Then check to see if we should lower the memcpy with target-specific 4629 // code. If the target chooses to do this, this is the next best. 4630 if (TSI) { 4631 SDValue Result = TSI->EmitTargetCodeForMemcpy( 4632 *this, dl, Chain, Dst, Src, Size, Align, isVol, AlwaysInline, 4633 DstPtrInfo, SrcPtrInfo); 4634 if (Result.getNode()) 4635 return Result; 4636 } 4637 4638 // If we really need inline code and the target declined to provide it, 4639 // use a (potentially long) sequence of loads and stores. 4640 if (AlwaysInline) { 4641 assert(ConstantSize && "AlwaysInline requires a constant size!"); 4642 return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src, 4643 ConstantSize->getZExtValue(), Align, isVol, 4644 true, DstPtrInfo, SrcPtrInfo); 4645 } 4646 4647 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 4648 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace()); 4649 4650 // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc 4651 // memcpy is not guaranteed to be safe. libc memcpys aren't required to 4652 // respect volatile, so they may do things like read or write memory 4653 // beyond the given memory regions. But fixing this isn't easy, and most 4654 // people don't care. 4655 4656 // Emit a library call. 4657 TargetLowering::ArgListTy Args; 4658 TargetLowering::ArgListEntry Entry; 4659 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 4660 Entry.Node = Dst; Args.push_back(Entry); 4661 Entry.Node = Src; Args.push_back(Entry); 4662 Entry.Node = Size; Args.push_back(Entry); 4663 // FIXME: pass in SDLoc 4664 TargetLowering::CallLoweringInfo CLI(*this); 4665 CLI.setDebugLoc(dl) 4666 .setChain(Chain) 4667 .setCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY), 4668 Dst.getValueType().getTypeForEVT(*getContext()), 4669 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY), 4670 TLI->getPointerTy(getDataLayout())), 4671 std::move(Args), 0) 4672 .setDiscardResult() 4673 .setTailCall(isTailCall); 4674 4675 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 4676 return CallResult.second; 4677 } 4678 4679 SDValue SelectionDAG::getMemmove(SDValue Chain, SDLoc dl, SDValue Dst, 4680 SDValue Src, SDValue Size, 4681 unsigned Align, bool isVol, bool isTailCall, 4682 MachinePointerInfo DstPtrInfo, 4683 MachinePointerInfo SrcPtrInfo) { 4684 assert(Align && "The SDAG layer expects explicit alignment and reserves 0"); 4685 4686 // Check to see if we should lower the memmove to loads and stores first. 4687 // For cases within the target-specified limits, this is the best choice. 4688 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 4689 if (ConstantSize) { 4690 // Memmove with size zero? Just return the original chain. 4691 if (ConstantSize->isNullValue()) 4692 return Chain; 4693 4694 SDValue Result = 4695 getMemmoveLoadsAndStores(*this, dl, Chain, Dst, Src, 4696 ConstantSize->getZExtValue(), Align, isVol, 4697 false, DstPtrInfo, SrcPtrInfo); 4698 if (Result.getNode()) 4699 return Result; 4700 } 4701 4702 // Then check to see if we should lower the memmove with target-specific 4703 // code. If the target chooses to do this, this is the next best. 4704 if (TSI) { 4705 SDValue Result = TSI->EmitTargetCodeForMemmove( 4706 *this, dl, Chain, Dst, Src, Size, Align, isVol, DstPtrInfo, SrcPtrInfo); 4707 if (Result.getNode()) 4708 return Result; 4709 } 4710 4711 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 4712 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace()); 4713 4714 // FIXME: If the memmove is volatile, lowering it to plain libc memmove may 4715 // not be safe. See memcpy above for more details. 4716 4717 // Emit a library call. 4718 TargetLowering::ArgListTy Args; 4719 TargetLowering::ArgListEntry Entry; 4720 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 4721 Entry.Node = Dst; Args.push_back(Entry); 4722 Entry.Node = Src; Args.push_back(Entry); 4723 Entry.Node = Size; Args.push_back(Entry); 4724 // FIXME: pass in SDLoc 4725 TargetLowering::CallLoweringInfo CLI(*this); 4726 CLI.setDebugLoc(dl) 4727 .setChain(Chain) 4728 .setCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE), 4729 Dst.getValueType().getTypeForEVT(*getContext()), 4730 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE), 4731 TLI->getPointerTy(getDataLayout())), 4732 std::move(Args), 0) 4733 .setDiscardResult() 4734 .setTailCall(isTailCall); 4735 4736 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 4737 return CallResult.second; 4738 } 4739 4740 SDValue SelectionDAG::getMemset(SDValue Chain, SDLoc dl, SDValue Dst, 4741 SDValue Src, SDValue Size, 4742 unsigned Align, bool isVol, bool isTailCall, 4743 MachinePointerInfo DstPtrInfo) { 4744 assert(Align && "The SDAG layer expects explicit alignment and reserves 0"); 4745 4746 // Check to see if we should lower the memset to stores first. 4747 // For cases within the target-specified limits, this is the best choice. 4748 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 4749 if (ConstantSize) { 4750 // Memset with size zero? Just return the original chain. 4751 if (ConstantSize->isNullValue()) 4752 return Chain; 4753 4754 SDValue Result = 4755 getMemsetStores(*this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), 4756 Align, isVol, DstPtrInfo); 4757 4758 if (Result.getNode()) 4759 return Result; 4760 } 4761 4762 // Then check to see if we should lower the memset with target-specific 4763 // code. If the target chooses to do this, this is the next best. 4764 if (TSI) { 4765 SDValue Result = TSI->EmitTargetCodeForMemset( 4766 *this, dl, Chain, Dst, Src, Size, Align, isVol, DstPtrInfo); 4767 if (Result.getNode()) 4768 return Result; 4769 } 4770 4771 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 4772 4773 // Emit a library call. 4774 Type *IntPtrTy = getDataLayout().getIntPtrType(*getContext()); 4775 TargetLowering::ArgListTy Args; 4776 TargetLowering::ArgListEntry Entry; 4777 Entry.Node = Dst; Entry.Ty = IntPtrTy; 4778 Args.push_back(Entry); 4779 Entry.Node = Src; 4780 Entry.Ty = Src.getValueType().getTypeForEVT(*getContext()); 4781 Args.push_back(Entry); 4782 Entry.Node = Size; 4783 Entry.Ty = IntPtrTy; 4784 Args.push_back(Entry); 4785 4786 // FIXME: pass in SDLoc 4787 TargetLowering::CallLoweringInfo CLI(*this); 4788 CLI.setDebugLoc(dl) 4789 .setChain(Chain) 4790 .setCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET), 4791 Dst.getValueType().getTypeForEVT(*getContext()), 4792 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET), 4793 TLI->getPointerTy(getDataLayout())), 4794 std::move(Args), 0) 4795 .setDiscardResult() 4796 .setTailCall(isTailCall); 4797 4798 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 4799 return CallResult.second; 4800 } 4801 4802 SDValue SelectionDAG::getAtomic(unsigned Opcode, SDLoc dl, EVT MemVT, 4803 SDVTList VTList, ArrayRef<SDValue> Ops, 4804 MachineMemOperand *MMO, 4805 AtomicOrdering SuccessOrdering, 4806 AtomicOrdering FailureOrdering, 4807 SynchronizationScope SynchScope) { 4808 FoldingSetNodeID ID; 4809 ID.AddInteger(MemVT.getRawBits()); 4810 AddNodeIDNode(ID, Opcode, VTList, Ops); 4811 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 4812 void* IP = nullptr; 4813 if (SDNode *E = FindNodeOrInsertPos(ID, dl.getDebugLoc(), IP)) { 4814 cast<AtomicSDNode>(E)->refineAlignment(MMO); 4815 return SDValue(E, 0); 4816 } 4817 4818 // Allocate the operands array for the node out of the BumpPtrAllocator, since 4819 // SDNode doesn't have access to it. This memory will be "leaked" when 4820 // the node is deallocated, but recovered when the allocator is released. 4821 // If the number of operands is less than 5 we use AtomicSDNode's internal 4822 // storage. 4823 unsigned NumOps = Ops.size(); 4824 SDUse *DynOps = NumOps > 4 ? OperandAllocator.Allocate<SDUse>(NumOps) 4825 : nullptr; 4826 4827 SDNode *N = new (NodeAllocator) AtomicSDNode(Opcode, dl.getIROrder(), 4828 dl.getDebugLoc(), VTList, MemVT, 4829 Ops.data(), DynOps, NumOps, MMO, 4830 SuccessOrdering, FailureOrdering, 4831 SynchScope); 4832 CSEMap.InsertNode(N, IP); 4833 InsertNode(N); 4834 return SDValue(N, 0); 4835 } 4836 4837 SDValue SelectionDAG::getAtomic(unsigned Opcode, SDLoc dl, EVT MemVT, 4838 SDVTList VTList, ArrayRef<SDValue> Ops, 4839 MachineMemOperand *MMO, 4840 AtomicOrdering Ordering, 4841 SynchronizationScope SynchScope) { 4842 return getAtomic(Opcode, dl, MemVT, VTList, Ops, MMO, Ordering, 4843 Ordering, SynchScope); 4844 } 4845 4846 SDValue SelectionDAG::getAtomicCmpSwap( 4847 unsigned Opcode, SDLoc dl, EVT MemVT, SDVTList VTs, SDValue Chain, 4848 SDValue Ptr, SDValue Cmp, SDValue Swp, MachinePointerInfo PtrInfo, 4849 unsigned Alignment, AtomicOrdering SuccessOrdering, 4850 AtomicOrdering FailureOrdering, SynchronizationScope SynchScope) { 4851 assert(Opcode == ISD::ATOMIC_CMP_SWAP || 4852 Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 4853 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types"); 4854 4855 if (Alignment == 0) // Ensure that codegen never sees alignment 0 4856 Alignment = getEVTAlignment(MemVT); 4857 4858 MachineFunction &MF = getMachineFunction(); 4859 4860 // FIXME: Volatile isn't really correct; we should keep track of atomic 4861 // orderings in the memoperand. 4862 unsigned Flags = MachineMemOperand::MOVolatile; 4863 Flags |= MachineMemOperand::MOLoad; 4864 Flags |= MachineMemOperand::MOStore; 4865 4866 MachineMemOperand *MMO = 4867 MF.getMachineMemOperand(PtrInfo, Flags, MemVT.getStoreSize(), Alignment); 4868 4869 return getAtomicCmpSwap(Opcode, dl, MemVT, VTs, Chain, Ptr, Cmp, Swp, MMO, 4870 SuccessOrdering, FailureOrdering, SynchScope); 4871 } 4872 4873 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, SDLoc dl, EVT MemVT, 4874 SDVTList VTs, SDValue Chain, SDValue Ptr, 4875 SDValue Cmp, SDValue Swp, 4876 MachineMemOperand *MMO, 4877 AtomicOrdering SuccessOrdering, 4878 AtomicOrdering FailureOrdering, 4879 SynchronizationScope SynchScope) { 4880 assert(Opcode == ISD::ATOMIC_CMP_SWAP || 4881 Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 4882 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types"); 4883 4884 SDValue Ops[] = {Chain, Ptr, Cmp, Swp}; 4885 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO, 4886 SuccessOrdering, FailureOrdering, SynchScope); 4887 } 4888 4889 SDValue SelectionDAG::getAtomic(unsigned Opcode, SDLoc dl, EVT MemVT, 4890 SDValue Chain, 4891 SDValue Ptr, SDValue Val, 4892 const Value* PtrVal, 4893 unsigned Alignment, 4894 AtomicOrdering Ordering, 4895 SynchronizationScope SynchScope) { 4896 if (Alignment == 0) // Ensure that codegen never sees alignment 0 4897 Alignment = getEVTAlignment(MemVT); 4898 4899 MachineFunction &MF = getMachineFunction(); 4900 // An atomic store does not load. An atomic load does not store. 4901 // (An atomicrmw obviously both loads and stores.) 4902 // For now, atomics are considered to be volatile always, and they are 4903 // chained as such. 4904 // FIXME: Volatile isn't really correct; we should keep track of atomic 4905 // orderings in the memoperand. 4906 unsigned Flags = MachineMemOperand::MOVolatile; 4907 if (Opcode != ISD::ATOMIC_STORE) 4908 Flags |= MachineMemOperand::MOLoad; 4909 if (Opcode != ISD::ATOMIC_LOAD) 4910 Flags |= MachineMemOperand::MOStore; 4911 4912 MachineMemOperand *MMO = 4913 MF.getMachineMemOperand(MachinePointerInfo(PtrVal), Flags, 4914 MemVT.getStoreSize(), Alignment); 4915 4916 return getAtomic(Opcode, dl, MemVT, Chain, Ptr, Val, MMO, 4917 Ordering, SynchScope); 4918 } 4919 4920 SDValue SelectionDAG::getAtomic(unsigned Opcode, SDLoc dl, EVT MemVT, 4921 SDValue Chain, 4922 SDValue Ptr, SDValue Val, 4923 MachineMemOperand *MMO, 4924 AtomicOrdering Ordering, 4925 SynchronizationScope SynchScope) { 4926 assert((Opcode == ISD::ATOMIC_LOAD_ADD || 4927 Opcode == ISD::ATOMIC_LOAD_SUB || 4928 Opcode == ISD::ATOMIC_LOAD_AND || 4929 Opcode == ISD::ATOMIC_LOAD_OR || 4930 Opcode == ISD::ATOMIC_LOAD_XOR || 4931 Opcode == ISD::ATOMIC_LOAD_NAND || 4932 Opcode == ISD::ATOMIC_LOAD_MIN || 4933 Opcode == ISD::ATOMIC_LOAD_MAX || 4934 Opcode == ISD::ATOMIC_LOAD_UMIN || 4935 Opcode == ISD::ATOMIC_LOAD_UMAX || 4936 Opcode == ISD::ATOMIC_SWAP || 4937 Opcode == ISD::ATOMIC_STORE) && 4938 "Invalid Atomic Op"); 4939 4940 EVT VT = Val.getValueType(); 4941 4942 SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) : 4943 getVTList(VT, MVT::Other); 4944 SDValue Ops[] = {Chain, Ptr, Val}; 4945 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO, Ordering, SynchScope); 4946 } 4947 4948 SDValue SelectionDAG::getAtomic(unsigned Opcode, SDLoc dl, EVT MemVT, 4949 EVT VT, SDValue Chain, 4950 SDValue Ptr, 4951 MachineMemOperand *MMO, 4952 AtomicOrdering Ordering, 4953 SynchronizationScope SynchScope) { 4954 assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op"); 4955 4956 SDVTList VTs = getVTList(VT, MVT::Other); 4957 SDValue Ops[] = {Chain, Ptr}; 4958 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO, Ordering, SynchScope); 4959 } 4960 4961 /// getMergeValues - Create a MERGE_VALUES node from the given operands. 4962 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, SDLoc dl) { 4963 if (Ops.size() == 1) 4964 return Ops[0]; 4965 4966 SmallVector<EVT, 4> VTs; 4967 VTs.reserve(Ops.size()); 4968 for (unsigned i = 0; i < Ops.size(); ++i) 4969 VTs.push_back(Ops[i].getValueType()); 4970 return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops); 4971 } 4972 4973 SDValue 4974 SelectionDAG::getMemIntrinsicNode(unsigned Opcode, SDLoc dl, SDVTList VTList, 4975 ArrayRef<SDValue> Ops, 4976 EVT MemVT, MachinePointerInfo PtrInfo, 4977 unsigned Align, bool Vol, 4978 bool ReadMem, bool WriteMem, unsigned Size) { 4979 if (Align == 0) // Ensure that codegen never sees alignment 0 4980 Align = getEVTAlignment(MemVT); 4981 4982 MachineFunction &MF = getMachineFunction(); 4983 unsigned Flags = 0; 4984 if (WriteMem) 4985 Flags |= MachineMemOperand::MOStore; 4986 if (ReadMem) 4987 Flags |= MachineMemOperand::MOLoad; 4988 if (Vol) 4989 Flags |= MachineMemOperand::MOVolatile; 4990 if (!Size) 4991 Size = MemVT.getStoreSize(); 4992 MachineMemOperand *MMO = 4993 MF.getMachineMemOperand(PtrInfo, Flags, Size, Align); 4994 4995 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO); 4996 } 4997 4998 SDValue 4999 SelectionDAG::getMemIntrinsicNode(unsigned Opcode, SDLoc dl, SDVTList VTList, 5000 ArrayRef<SDValue> Ops, EVT MemVT, 5001 MachineMemOperand *MMO) { 5002 assert((Opcode == ISD::INTRINSIC_VOID || 5003 Opcode == ISD::INTRINSIC_W_CHAIN || 5004 Opcode == ISD::PREFETCH || 5005 Opcode == ISD::LIFETIME_START || 5006 Opcode == ISD::LIFETIME_END || 5007 (Opcode <= INT_MAX && 5008 (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) && 5009 "Opcode is not a memory-accessing opcode!"); 5010 5011 // Memoize the node unless it returns a flag. 5012 MemIntrinsicSDNode *N; 5013 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) { 5014 FoldingSetNodeID ID; 5015 AddNodeIDNode(ID, Opcode, VTList, Ops); 5016 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 5017 void *IP = nullptr; 5018 if (SDNode *E = FindNodeOrInsertPos(ID, dl.getDebugLoc(), IP)) { 5019 cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO); 5020 return SDValue(E, 0); 5021 } 5022 5023 N = new (NodeAllocator) MemIntrinsicSDNode(Opcode, dl.getIROrder(), 5024 dl.getDebugLoc(), VTList, Ops, 5025 MemVT, MMO); 5026 CSEMap.InsertNode(N, IP); 5027 } else { 5028 N = new (NodeAllocator) MemIntrinsicSDNode(Opcode, dl.getIROrder(), 5029 dl.getDebugLoc(), VTList, Ops, 5030 MemVT, MMO); 5031 } 5032 InsertNode(N); 5033 return SDValue(N, 0); 5034 } 5035 5036 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a 5037 /// MachinePointerInfo record from it. This is particularly useful because the 5038 /// code generator has many cases where it doesn't bother passing in a 5039 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst". 5040 static MachinePointerInfo InferPointerInfo(SelectionDAG &DAG, SDValue Ptr, 5041 int64_t Offset = 0) { 5042 // If this is FI+Offset, we can model it. 5043 if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) 5044 return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), 5045 FI->getIndex(), Offset); 5046 5047 // If this is (FI+Offset1)+Offset2, we can model it. 5048 if (Ptr.getOpcode() != ISD::ADD || 5049 !isa<ConstantSDNode>(Ptr.getOperand(1)) || 5050 !isa<FrameIndexSDNode>(Ptr.getOperand(0))) 5051 return MachinePointerInfo(); 5052 5053 int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex(); 5054 return MachinePointerInfo::getFixedStack( 5055 DAG.getMachineFunction(), FI, 5056 Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue()); 5057 } 5058 5059 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a 5060 /// MachinePointerInfo record from it. This is particularly useful because the 5061 /// code generator has many cases where it doesn't bother passing in a 5062 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst". 5063 static MachinePointerInfo InferPointerInfo(SelectionDAG &DAG, SDValue Ptr, 5064 SDValue OffsetOp) { 5065 // If the 'Offset' value isn't a constant, we can't handle this. 5066 if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp)) 5067 return InferPointerInfo(DAG, Ptr, OffsetNode->getSExtValue()); 5068 if (OffsetOp.getOpcode() == ISD::UNDEF) 5069 return InferPointerInfo(DAG, Ptr); 5070 return MachinePointerInfo(); 5071 } 5072 5073 5074 SDValue 5075 SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, 5076 EVT VT, SDLoc dl, SDValue Chain, 5077 SDValue Ptr, SDValue Offset, 5078 MachinePointerInfo PtrInfo, EVT MemVT, 5079 bool isVolatile, bool isNonTemporal, bool isInvariant, 5080 unsigned Alignment, const AAMDNodes &AAInfo, 5081 const MDNode *Ranges) { 5082 assert(Chain.getValueType() == MVT::Other && 5083 "Invalid chain type"); 5084 if (Alignment == 0) // Ensure that codegen never sees alignment 0 5085 Alignment = getEVTAlignment(VT); 5086 5087 unsigned Flags = MachineMemOperand::MOLoad; 5088 if (isVolatile) 5089 Flags |= MachineMemOperand::MOVolatile; 5090 if (isNonTemporal) 5091 Flags |= MachineMemOperand::MONonTemporal; 5092 if (isInvariant) 5093 Flags |= MachineMemOperand::MOInvariant; 5094 5095 // If we don't have a PtrInfo, infer the trivial frame index case to simplify 5096 // clients. 5097 if (PtrInfo.V.isNull()) 5098 PtrInfo = InferPointerInfo(*this, Ptr, Offset); 5099 5100 MachineFunction &MF = getMachineFunction(); 5101 MachineMemOperand *MMO = 5102 MF.getMachineMemOperand(PtrInfo, Flags, MemVT.getStoreSize(), Alignment, 5103 AAInfo, Ranges); 5104 return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO); 5105 } 5106 5107 SDValue 5108 SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, 5109 EVT VT, SDLoc dl, SDValue Chain, 5110 SDValue Ptr, SDValue Offset, EVT MemVT, 5111 MachineMemOperand *MMO) { 5112 if (VT == MemVT) { 5113 ExtType = ISD::NON_EXTLOAD; 5114 } else if (ExtType == ISD::NON_EXTLOAD) { 5115 assert(VT == MemVT && "Non-extending load from different memory type!"); 5116 } else { 5117 // Extending load. 5118 assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) && 5119 "Should only be an extending load, not truncating!"); 5120 assert(VT.isInteger() == MemVT.isInteger() && 5121 "Cannot convert from FP to Int or Int -> FP!"); 5122 assert(VT.isVector() == MemVT.isVector() && 5123 "Cannot use an ext load to convert to or from a vector!"); 5124 assert((!VT.isVector() || 5125 VT.getVectorNumElements() == MemVT.getVectorNumElements()) && 5126 "Cannot use an ext load to change the number of vector elements!"); 5127 } 5128 5129 bool Indexed = AM != ISD::UNINDEXED; 5130 assert((Indexed || Offset.getOpcode() == ISD::UNDEF) && 5131 "Unindexed load with an offset!"); 5132 5133 SDVTList VTs = Indexed ? 5134 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other); 5135 SDValue Ops[] = { Chain, Ptr, Offset }; 5136 FoldingSetNodeID ID; 5137 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops); 5138 ID.AddInteger(MemVT.getRawBits()); 5139 ID.AddInteger(encodeMemSDNodeFlags(ExtType, AM, MMO->isVolatile(), 5140 MMO->isNonTemporal(), 5141 MMO->isInvariant())); 5142 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 5143 void *IP = nullptr; 5144 if (SDNode *E = FindNodeOrInsertPos(ID, dl.getDebugLoc(), IP)) { 5145 cast<LoadSDNode>(E)->refineAlignment(MMO); 5146 return SDValue(E, 0); 5147 } 5148 SDNode *N = new (NodeAllocator) LoadSDNode(Ops, dl.getIROrder(), 5149 dl.getDebugLoc(), VTs, AM, ExtType, 5150 MemVT, MMO); 5151 CSEMap.InsertNode(N, IP); 5152 InsertNode(N); 5153 return SDValue(N, 0); 5154 } 5155 5156 SDValue SelectionDAG::getLoad(EVT VT, SDLoc dl, 5157 SDValue Chain, SDValue Ptr, 5158 MachinePointerInfo PtrInfo, 5159 bool isVolatile, bool isNonTemporal, 5160 bool isInvariant, unsigned Alignment, 5161 const AAMDNodes &AAInfo, 5162 const MDNode *Ranges) { 5163 SDValue Undef = getUNDEF(Ptr.getValueType()); 5164 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 5165 PtrInfo, VT, isVolatile, isNonTemporal, isInvariant, Alignment, 5166 AAInfo, Ranges); 5167 } 5168 5169 SDValue SelectionDAG::getLoad(EVT VT, SDLoc dl, 5170 SDValue Chain, SDValue Ptr, 5171 MachineMemOperand *MMO) { 5172 SDValue Undef = getUNDEF(Ptr.getValueType()); 5173 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 5174 VT, MMO); 5175 } 5176 5177 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, SDLoc dl, EVT VT, 5178 SDValue Chain, SDValue Ptr, 5179 MachinePointerInfo PtrInfo, EVT MemVT, 5180 bool isVolatile, bool isNonTemporal, 5181 bool isInvariant, unsigned Alignment, 5182 const AAMDNodes &AAInfo) { 5183 SDValue Undef = getUNDEF(Ptr.getValueType()); 5184 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, 5185 PtrInfo, MemVT, isVolatile, isNonTemporal, isInvariant, 5186 Alignment, AAInfo); 5187 } 5188 5189 5190 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, SDLoc dl, EVT VT, 5191 SDValue Chain, SDValue Ptr, EVT MemVT, 5192 MachineMemOperand *MMO) { 5193 SDValue Undef = getUNDEF(Ptr.getValueType()); 5194 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, 5195 MemVT, MMO); 5196 } 5197 5198 SDValue 5199 SelectionDAG::getIndexedLoad(SDValue OrigLoad, SDLoc dl, SDValue Base, 5200 SDValue Offset, ISD::MemIndexedMode AM) { 5201 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad); 5202 assert(LD->getOffset().getOpcode() == ISD::UNDEF && 5203 "Load is already a indexed load!"); 5204 return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl, 5205 LD->getChain(), Base, Offset, LD->getPointerInfo(), 5206 LD->getMemoryVT(), LD->isVolatile(), LD->isNonTemporal(), 5207 false, LD->getAlignment()); 5208 } 5209 5210 SDValue SelectionDAG::getStore(SDValue Chain, SDLoc dl, SDValue Val, 5211 SDValue Ptr, MachinePointerInfo PtrInfo, 5212 bool isVolatile, bool isNonTemporal, 5213 unsigned Alignment, const AAMDNodes &AAInfo) { 5214 assert(Chain.getValueType() == MVT::Other && 5215 "Invalid chain type"); 5216 if (Alignment == 0) // Ensure that codegen never sees alignment 0 5217 Alignment = getEVTAlignment(Val.getValueType()); 5218 5219 unsigned Flags = MachineMemOperand::MOStore; 5220 if (isVolatile) 5221 Flags |= MachineMemOperand::MOVolatile; 5222 if (isNonTemporal) 5223 Flags |= MachineMemOperand::MONonTemporal; 5224 5225 if (PtrInfo.V.isNull()) 5226 PtrInfo = InferPointerInfo(*this, Ptr); 5227 5228 MachineFunction &MF = getMachineFunction(); 5229 MachineMemOperand *MMO = 5230 MF.getMachineMemOperand(PtrInfo, Flags, 5231 Val.getValueType().getStoreSize(), Alignment, 5232 AAInfo); 5233 5234 return getStore(Chain, dl, Val, Ptr, MMO); 5235 } 5236 5237 SDValue SelectionDAG::getStore(SDValue Chain, SDLoc dl, SDValue Val, 5238 SDValue Ptr, MachineMemOperand *MMO) { 5239 assert(Chain.getValueType() == MVT::Other && 5240 "Invalid chain type"); 5241 EVT VT = Val.getValueType(); 5242 SDVTList VTs = getVTList(MVT::Other); 5243 SDValue Undef = getUNDEF(Ptr.getValueType()); 5244 SDValue Ops[] = { Chain, Val, Ptr, Undef }; 5245 FoldingSetNodeID ID; 5246 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 5247 ID.AddInteger(VT.getRawBits()); 5248 ID.AddInteger(encodeMemSDNodeFlags(false, ISD::UNINDEXED, MMO->isVolatile(), 5249 MMO->isNonTemporal(), MMO->isInvariant())); 5250 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 5251 void *IP = nullptr; 5252 if (SDNode *E = FindNodeOrInsertPos(ID, dl.getDebugLoc(), IP)) { 5253 cast<StoreSDNode>(E)->refineAlignment(MMO); 5254 return SDValue(E, 0); 5255 } 5256 SDNode *N = new (NodeAllocator) StoreSDNode(Ops, dl.getIROrder(), 5257 dl.getDebugLoc(), VTs, 5258 ISD::UNINDEXED, false, VT, MMO); 5259 CSEMap.InsertNode(N, IP); 5260 InsertNode(N); 5261 return SDValue(N, 0); 5262 } 5263 5264 SDValue SelectionDAG::getTruncStore(SDValue Chain, SDLoc dl, SDValue Val, 5265 SDValue Ptr, MachinePointerInfo PtrInfo, 5266 EVT SVT,bool isVolatile, bool isNonTemporal, 5267 unsigned Alignment, 5268 const AAMDNodes &AAInfo) { 5269 assert(Chain.getValueType() == MVT::Other && 5270 "Invalid chain type"); 5271 if (Alignment == 0) // Ensure that codegen never sees alignment 0 5272 Alignment = getEVTAlignment(SVT); 5273 5274 unsigned Flags = MachineMemOperand::MOStore; 5275 if (isVolatile) 5276 Flags |= MachineMemOperand::MOVolatile; 5277 if (isNonTemporal) 5278 Flags |= MachineMemOperand::MONonTemporal; 5279 5280 if (PtrInfo.V.isNull()) 5281 PtrInfo = InferPointerInfo(*this, Ptr); 5282 5283 MachineFunction &MF = getMachineFunction(); 5284 MachineMemOperand *MMO = 5285 MF.getMachineMemOperand(PtrInfo, Flags, SVT.getStoreSize(), Alignment, 5286 AAInfo); 5287 5288 return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO); 5289 } 5290 5291 SDValue SelectionDAG::getTruncStore(SDValue Chain, SDLoc dl, SDValue Val, 5292 SDValue Ptr, EVT SVT, 5293 MachineMemOperand *MMO) { 5294 EVT VT = Val.getValueType(); 5295 5296 assert(Chain.getValueType() == MVT::Other && 5297 "Invalid chain type"); 5298 if (VT == SVT) 5299 return getStore(Chain, dl, Val, Ptr, MMO); 5300 5301 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) && 5302 "Should only be a truncating store, not extending!"); 5303 assert(VT.isInteger() == SVT.isInteger() && 5304 "Can't do FP-INT conversion!"); 5305 assert(VT.isVector() == SVT.isVector() && 5306 "Cannot use trunc store to convert to or from a vector!"); 5307 assert((!VT.isVector() || 5308 VT.getVectorNumElements() == SVT.getVectorNumElements()) && 5309 "Cannot use trunc store to change the number of vector elements!"); 5310 5311 SDVTList VTs = getVTList(MVT::Other); 5312 SDValue Undef = getUNDEF(Ptr.getValueType()); 5313 SDValue Ops[] = { Chain, Val, Ptr, Undef }; 5314 FoldingSetNodeID ID; 5315 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 5316 ID.AddInteger(SVT.getRawBits()); 5317 ID.AddInteger(encodeMemSDNodeFlags(true, ISD::UNINDEXED, MMO->isVolatile(), 5318 MMO->isNonTemporal(), MMO->isInvariant())); 5319 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 5320 void *IP = nullptr; 5321 if (SDNode *E = FindNodeOrInsertPos(ID, dl.getDebugLoc(), IP)) { 5322 cast<StoreSDNode>(E)->refineAlignment(MMO); 5323 return SDValue(E, 0); 5324 } 5325 SDNode *N = new (NodeAllocator) StoreSDNode(Ops, dl.getIROrder(), 5326 dl.getDebugLoc(), VTs, 5327 ISD::UNINDEXED, true, SVT, MMO); 5328 CSEMap.InsertNode(N, IP); 5329 InsertNode(N); 5330 return SDValue(N, 0); 5331 } 5332 5333 SDValue 5334 SelectionDAG::getIndexedStore(SDValue OrigStore, SDLoc dl, SDValue Base, 5335 SDValue Offset, ISD::MemIndexedMode AM) { 5336 StoreSDNode *ST = cast<StoreSDNode>(OrigStore); 5337 assert(ST->getOffset().getOpcode() == ISD::UNDEF && 5338 "Store is already a indexed store!"); 5339 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other); 5340 SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset }; 5341 FoldingSetNodeID ID; 5342 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 5343 ID.AddInteger(ST->getMemoryVT().getRawBits()); 5344 ID.AddInteger(ST->getRawSubclassData()); 5345 ID.AddInteger(ST->getPointerInfo().getAddrSpace()); 5346 void *IP = nullptr; 5347 if (SDNode *E = FindNodeOrInsertPos(ID, dl.getDebugLoc(), IP)) 5348 return SDValue(E, 0); 5349 5350 SDNode *N = new (NodeAllocator) StoreSDNode(Ops, dl.getIROrder(), 5351 dl.getDebugLoc(), VTs, AM, 5352 ST->isTruncatingStore(), 5353 ST->getMemoryVT(), 5354 ST->getMemOperand()); 5355 CSEMap.InsertNode(N, IP); 5356 InsertNode(N); 5357 return SDValue(N, 0); 5358 } 5359 5360 SDValue 5361 SelectionDAG::getMaskedLoad(EVT VT, SDLoc dl, SDValue Chain, 5362 SDValue Ptr, SDValue Mask, SDValue Src0, EVT MemVT, 5363 MachineMemOperand *MMO, ISD::LoadExtType ExtTy) { 5364 5365 SDVTList VTs = getVTList(VT, MVT::Other); 5366 SDValue Ops[] = { Chain, Ptr, Mask, Src0 }; 5367 FoldingSetNodeID ID; 5368 AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops); 5369 ID.AddInteger(VT.getRawBits()); 5370 ID.AddInteger(encodeMemSDNodeFlags(ExtTy, ISD::UNINDEXED, 5371 MMO->isVolatile(), 5372 MMO->isNonTemporal(), 5373 MMO->isInvariant())); 5374 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 5375 void *IP = nullptr; 5376 if (SDNode *E = FindNodeOrInsertPos(ID, dl.getDebugLoc(), IP)) { 5377 cast<MaskedLoadSDNode>(E)->refineAlignment(MMO); 5378 return SDValue(E, 0); 5379 } 5380 SDNode *N = new (NodeAllocator) MaskedLoadSDNode(dl.getIROrder(), 5381 dl.getDebugLoc(), Ops, 4, VTs, 5382 ExtTy, MemVT, MMO); 5383 CSEMap.InsertNode(N, IP); 5384 InsertNode(N); 5385 return SDValue(N, 0); 5386 } 5387 5388 SDValue SelectionDAG::getMaskedStore(SDValue Chain, SDLoc dl, SDValue Val, 5389 SDValue Ptr, SDValue Mask, EVT MemVT, 5390 MachineMemOperand *MMO, bool isTrunc) { 5391 assert(Chain.getValueType() == MVT::Other && 5392 "Invalid chain type"); 5393 EVT VT = Val.getValueType(); 5394 SDVTList VTs = getVTList(MVT::Other); 5395 SDValue Ops[] = { Chain, Ptr, Mask, Val }; 5396 FoldingSetNodeID ID; 5397 AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops); 5398 ID.AddInteger(VT.getRawBits()); 5399 ID.AddInteger(encodeMemSDNodeFlags(false, ISD::UNINDEXED, MMO->isVolatile(), 5400 MMO->isNonTemporal(), MMO->isInvariant())); 5401 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 5402 void *IP = nullptr; 5403 if (SDNode *E = FindNodeOrInsertPos(ID, dl.getDebugLoc(), IP)) { 5404 cast<MaskedStoreSDNode>(E)->refineAlignment(MMO); 5405 return SDValue(E, 0); 5406 } 5407 SDNode *N = new (NodeAllocator) MaskedStoreSDNode(dl.getIROrder(), 5408 dl.getDebugLoc(), Ops, 4, 5409 VTs, isTrunc, MemVT, MMO); 5410 CSEMap.InsertNode(N, IP); 5411 InsertNode(N); 5412 return SDValue(N, 0); 5413 } 5414 5415 SDValue 5416 SelectionDAG::getMaskedGather(SDVTList VTs, EVT VT, SDLoc dl, 5417 ArrayRef<SDValue> Ops, 5418 MachineMemOperand *MMO) { 5419 5420 FoldingSetNodeID ID; 5421 AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops); 5422 ID.AddInteger(VT.getRawBits()); 5423 ID.AddInteger(encodeMemSDNodeFlags(ISD::NON_EXTLOAD, ISD::UNINDEXED, 5424 MMO->isVolatile(), 5425 MMO->isNonTemporal(), 5426 MMO->isInvariant())); 5427 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 5428 void *IP = nullptr; 5429 if (SDNode *E = FindNodeOrInsertPos(ID, dl.getDebugLoc(), IP)) { 5430 cast<MaskedGatherSDNode>(E)->refineAlignment(MMO); 5431 return SDValue(E, 0); 5432 } 5433 MaskedGatherSDNode *N = 5434 new (NodeAllocator) MaskedGatherSDNode(dl.getIROrder(), dl.getDebugLoc(), 5435 Ops, VTs, VT, MMO); 5436 CSEMap.InsertNode(N, IP); 5437 InsertNode(N); 5438 return SDValue(N, 0); 5439 } 5440 5441 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT VT, SDLoc dl, 5442 ArrayRef<SDValue> Ops, 5443 MachineMemOperand *MMO) { 5444 FoldingSetNodeID ID; 5445 AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops); 5446 ID.AddInteger(VT.getRawBits()); 5447 ID.AddInteger(encodeMemSDNodeFlags(false, ISD::UNINDEXED, MMO->isVolatile(), 5448 MMO->isNonTemporal(), 5449 MMO->isInvariant())); 5450 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 5451 void *IP = nullptr; 5452 if (SDNode *E = FindNodeOrInsertPos(ID, dl.getDebugLoc(), IP)) { 5453 cast<MaskedScatterSDNode>(E)->refineAlignment(MMO); 5454 return SDValue(E, 0); 5455 } 5456 SDNode *N = 5457 new (NodeAllocator) MaskedScatterSDNode(dl.getIROrder(), dl.getDebugLoc(), 5458 Ops, VTs, VT, MMO); 5459 CSEMap.InsertNode(N, IP); 5460 InsertNode(N); 5461 return SDValue(N, 0); 5462 } 5463 5464 SDValue SelectionDAG::getVAArg(EVT VT, SDLoc dl, 5465 SDValue Chain, SDValue Ptr, 5466 SDValue SV, 5467 unsigned Align) { 5468 SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) }; 5469 return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops); 5470 } 5471 5472 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, EVT VT, 5473 ArrayRef<SDUse> Ops) { 5474 switch (Ops.size()) { 5475 case 0: return getNode(Opcode, DL, VT); 5476 case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0])); 5477 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]); 5478 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]); 5479 default: break; 5480 } 5481 5482 // Copy from an SDUse array into an SDValue array for use with 5483 // the regular getNode logic. 5484 SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end()); 5485 return getNode(Opcode, DL, VT, NewOps); 5486 } 5487 5488 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, EVT VT, 5489 ArrayRef<SDValue> Ops, const SDNodeFlags *Flags) { 5490 unsigned NumOps = Ops.size(); 5491 switch (NumOps) { 5492 case 0: return getNode(Opcode, DL, VT); 5493 case 1: return getNode(Opcode, DL, VT, Ops[0]); 5494 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags); 5495 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]); 5496 default: break; 5497 } 5498 5499 switch (Opcode) { 5500 default: break; 5501 case ISD::CONCAT_VECTORS: { 5502 // Attempt to fold CONCAT_VECTORS into BUILD_VECTOR or UNDEF. 5503 if (SDValue V = FoldCONCAT_VECTORS(DL, VT, Ops, *this)) 5504 return V; 5505 break; 5506 } 5507 case ISD::SELECT_CC: { 5508 assert(NumOps == 5 && "SELECT_CC takes 5 operands!"); 5509 assert(Ops[0].getValueType() == Ops[1].getValueType() && 5510 "LHS and RHS of condition must have same type!"); 5511 assert(Ops[2].getValueType() == Ops[3].getValueType() && 5512 "True and False arms of SelectCC must have same type!"); 5513 assert(Ops[2].getValueType() == VT && 5514 "select_cc node must be of same type as true and false value!"); 5515 break; 5516 } 5517 case ISD::BR_CC: { 5518 assert(NumOps == 5 && "BR_CC takes 5 operands!"); 5519 assert(Ops[2].getValueType() == Ops[3].getValueType() && 5520 "LHS/RHS of comparison should match types!"); 5521 break; 5522 } 5523 } 5524 5525 // Memoize nodes. 5526 SDNode *N; 5527 SDVTList VTs = getVTList(VT); 5528 5529 if (VT != MVT::Glue) { 5530 FoldingSetNodeID ID; 5531 AddNodeIDNode(ID, Opcode, VTs, Ops); 5532 void *IP = nullptr; 5533 5534 if (SDNode *E = FindNodeOrInsertPos(ID, DL.getDebugLoc(), IP)) 5535 return SDValue(E, 0); 5536 5537 N = new (NodeAllocator) SDNode(Opcode, DL.getIROrder(), DL.getDebugLoc(), 5538 VTs, Ops); 5539 CSEMap.InsertNode(N, IP); 5540 } else { 5541 N = new (NodeAllocator) SDNode(Opcode, DL.getIROrder(), DL.getDebugLoc(), 5542 VTs, Ops); 5543 } 5544 5545 InsertNode(N); 5546 return SDValue(N, 0); 5547 } 5548 5549 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, 5550 ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) { 5551 return getNode(Opcode, DL, getVTList(ResultTys), Ops); 5552 } 5553 5554 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, SDVTList VTList, 5555 ArrayRef<SDValue> Ops) { 5556 if (VTList.NumVTs == 1) 5557 return getNode(Opcode, DL, VTList.VTs[0], Ops); 5558 5559 #if 0 5560 switch (Opcode) { 5561 // FIXME: figure out how to safely handle things like 5562 // int foo(int x) { return 1 << (x & 255); } 5563 // int bar() { return foo(256); } 5564 case ISD::SRA_PARTS: 5565 case ISD::SRL_PARTS: 5566 case ISD::SHL_PARTS: 5567 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG && 5568 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1) 5569 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0)); 5570 else if (N3.getOpcode() == ISD::AND) 5571 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) { 5572 // If the and is only masking out bits that cannot effect the shift, 5573 // eliminate the and. 5574 unsigned NumBits = VT.getScalarType().getSizeInBits()*2; 5575 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1) 5576 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0)); 5577 } 5578 break; 5579 } 5580 #endif 5581 5582 // Memoize the node unless it returns a flag. 5583 SDNode *N; 5584 unsigned NumOps = Ops.size(); 5585 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) { 5586 FoldingSetNodeID ID; 5587 AddNodeIDNode(ID, Opcode, VTList, Ops); 5588 void *IP = nullptr; 5589 if (SDNode *E = FindNodeOrInsertPos(ID, DL.getDebugLoc(), IP)) 5590 return SDValue(E, 0); 5591 5592 if (NumOps == 1) { 5593 N = new (NodeAllocator) UnarySDNode(Opcode, DL.getIROrder(), 5594 DL.getDebugLoc(), VTList, Ops[0]); 5595 } else if (NumOps == 2) { 5596 N = new (NodeAllocator) BinarySDNode(Opcode, DL.getIROrder(), 5597 DL.getDebugLoc(), VTList, Ops[0], 5598 Ops[1]); 5599 } else if (NumOps == 3) { 5600 N = new (NodeAllocator) TernarySDNode(Opcode, DL.getIROrder(), 5601 DL.getDebugLoc(), VTList, Ops[0], 5602 Ops[1], Ops[2]); 5603 } else { 5604 N = new (NodeAllocator) SDNode(Opcode, DL.getIROrder(), DL.getDebugLoc(), 5605 VTList, Ops); 5606 } 5607 CSEMap.InsertNode(N, IP); 5608 } else { 5609 if (NumOps == 1) { 5610 N = new (NodeAllocator) UnarySDNode(Opcode, DL.getIROrder(), 5611 DL.getDebugLoc(), VTList, Ops[0]); 5612 } else if (NumOps == 2) { 5613 N = new (NodeAllocator) BinarySDNode(Opcode, DL.getIROrder(), 5614 DL.getDebugLoc(), VTList, Ops[0], 5615 Ops[1]); 5616 } else if (NumOps == 3) { 5617 N = new (NodeAllocator) TernarySDNode(Opcode, DL.getIROrder(), 5618 DL.getDebugLoc(), VTList, Ops[0], 5619 Ops[1], Ops[2]); 5620 } else { 5621 N = new (NodeAllocator) SDNode(Opcode, DL.getIROrder(), DL.getDebugLoc(), 5622 VTList, Ops); 5623 } 5624 } 5625 InsertNode(N); 5626 return SDValue(N, 0); 5627 } 5628 5629 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, SDVTList VTList) { 5630 return getNode(Opcode, DL, VTList, None); 5631 } 5632 5633 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, SDVTList VTList, 5634 SDValue N1) { 5635 SDValue Ops[] = { N1 }; 5636 return getNode(Opcode, DL, VTList, Ops); 5637 } 5638 5639 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, SDVTList VTList, 5640 SDValue N1, SDValue N2) { 5641 SDValue Ops[] = { N1, N2 }; 5642 return getNode(Opcode, DL, VTList, Ops); 5643 } 5644 5645 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, SDVTList VTList, 5646 SDValue N1, SDValue N2, SDValue N3) { 5647 SDValue Ops[] = { N1, N2, N3 }; 5648 return getNode(Opcode, DL, VTList, Ops); 5649 } 5650 5651 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, SDVTList VTList, 5652 SDValue N1, SDValue N2, SDValue N3, 5653 SDValue N4) { 5654 SDValue Ops[] = { N1, N2, N3, N4 }; 5655 return getNode(Opcode, DL, VTList, Ops); 5656 } 5657 5658 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, SDVTList VTList, 5659 SDValue N1, SDValue N2, SDValue N3, 5660 SDValue N4, SDValue N5) { 5661 SDValue Ops[] = { N1, N2, N3, N4, N5 }; 5662 return getNode(Opcode, DL, VTList, Ops); 5663 } 5664 5665 SDVTList SelectionDAG::getVTList(EVT VT) { 5666 return makeVTList(SDNode::getValueTypeList(VT), 1); 5667 } 5668 5669 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) { 5670 FoldingSetNodeID ID; 5671 ID.AddInteger(2U); 5672 ID.AddInteger(VT1.getRawBits()); 5673 ID.AddInteger(VT2.getRawBits()); 5674 5675 void *IP = nullptr; 5676 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 5677 if (!Result) { 5678 EVT *Array = Allocator.Allocate<EVT>(2); 5679 Array[0] = VT1; 5680 Array[1] = VT2; 5681 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2); 5682 VTListMap.InsertNode(Result, IP); 5683 } 5684 return Result->getSDVTList(); 5685 } 5686 5687 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) { 5688 FoldingSetNodeID ID; 5689 ID.AddInteger(3U); 5690 ID.AddInteger(VT1.getRawBits()); 5691 ID.AddInteger(VT2.getRawBits()); 5692 ID.AddInteger(VT3.getRawBits()); 5693 5694 void *IP = nullptr; 5695 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 5696 if (!Result) { 5697 EVT *Array = Allocator.Allocate<EVT>(3); 5698 Array[0] = VT1; 5699 Array[1] = VT2; 5700 Array[2] = VT3; 5701 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3); 5702 VTListMap.InsertNode(Result, IP); 5703 } 5704 return Result->getSDVTList(); 5705 } 5706 5707 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) { 5708 FoldingSetNodeID ID; 5709 ID.AddInteger(4U); 5710 ID.AddInteger(VT1.getRawBits()); 5711 ID.AddInteger(VT2.getRawBits()); 5712 ID.AddInteger(VT3.getRawBits()); 5713 ID.AddInteger(VT4.getRawBits()); 5714 5715 void *IP = nullptr; 5716 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 5717 if (!Result) { 5718 EVT *Array = Allocator.Allocate<EVT>(4); 5719 Array[0] = VT1; 5720 Array[1] = VT2; 5721 Array[2] = VT3; 5722 Array[3] = VT4; 5723 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4); 5724 VTListMap.InsertNode(Result, IP); 5725 } 5726 return Result->getSDVTList(); 5727 } 5728 5729 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) { 5730 unsigned NumVTs = VTs.size(); 5731 FoldingSetNodeID ID; 5732 ID.AddInteger(NumVTs); 5733 for (unsigned index = 0; index < NumVTs; index++) { 5734 ID.AddInteger(VTs[index].getRawBits()); 5735 } 5736 5737 void *IP = nullptr; 5738 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 5739 if (!Result) { 5740 EVT *Array = Allocator.Allocate<EVT>(NumVTs); 5741 std::copy(VTs.begin(), VTs.end(), Array); 5742 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs); 5743 VTListMap.InsertNode(Result, IP); 5744 } 5745 return Result->getSDVTList(); 5746 } 5747 5748 5749 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the 5750 /// specified operands. If the resultant node already exists in the DAG, 5751 /// this does not modify the specified node, instead it returns the node that 5752 /// already exists. If the resultant node does not exist in the DAG, the 5753 /// input node is returned. As a degenerate case, if you specify the same 5754 /// input operands as the node already has, the input node is returned. 5755 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) { 5756 assert(N->getNumOperands() == 1 && "Update with wrong number of operands"); 5757 5758 // Check to see if there is no change. 5759 if (Op == N->getOperand(0)) return N; 5760 5761 // See if the modified node already exists. 5762 void *InsertPos = nullptr; 5763 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos)) 5764 return Existing; 5765 5766 // Nope it doesn't. Remove the node from its current place in the maps. 5767 if (InsertPos) 5768 if (!RemoveNodeFromCSEMaps(N)) 5769 InsertPos = nullptr; 5770 5771 // Now we update the operands. 5772 N->OperandList[0].set(Op); 5773 5774 // If this gets put into a CSE map, add it. 5775 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 5776 return N; 5777 } 5778 5779 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) { 5780 assert(N->getNumOperands() == 2 && "Update with wrong number of operands"); 5781 5782 // Check to see if there is no change. 5783 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1)) 5784 return N; // No operands changed, just return the input node. 5785 5786 // See if the modified node already exists. 5787 void *InsertPos = nullptr; 5788 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos)) 5789 return Existing; 5790 5791 // Nope it doesn't. Remove the node from its current place in the maps. 5792 if (InsertPos) 5793 if (!RemoveNodeFromCSEMaps(N)) 5794 InsertPos = nullptr; 5795 5796 // Now we update the operands. 5797 if (N->OperandList[0] != Op1) 5798 N->OperandList[0].set(Op1); 5799 if (N->OperandList[1] != Op2) 5800 N->OperandList[1].set(Op2); 5801 5802 // If this gets put into a CSE map, add it. 5803 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 5804 return N; 5805 } 5806 5807 SDNode *SelectionDAG:: 5808 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) { 5809 SDValue Ops[] = { Op1, Op2, Op3 }; 5810 return UpdateNodeOperands(N, Ops); 5811 } 5812 5813 SDNode *SelectionDAG:: 5814 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, 5815 SDValue Op3, SDValue Op4) { 5816 SDValue Ops[] = { Op1, Op2, Op3, Op4 }; 5817 return UpdateNodeOperands(N, Ops); 5818 } 5819 5820 SDNode *SelectionDAG:: 5821 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, 5822 SDValue Op3, SDValue Op4, SDValue Op5) { 5823 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 }; 5824 return UpdateNodeOperands(N, Ops); 5825 } 5826 5827 SDNode *SelectionDAG:: 5828 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) { 5829 unsigned NumOps = Ops.size(); 5830 assert(N->getNumOperands() == NumOps && 5831 "Update with wrong number of operands"); 5832 5833 // If no operands changed just return the input node. 5834 if (std::equal(Ops.begin(), Ops.end(), N->op_begin())) 5835 return N; 5836 5837 // See if the modified node already exists. 5838 void *InsertPos = nullptr; 5839 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos)) 5840 return Existing; 5841 5842 // Nope it doesn't. Remove the node from its current place in the maps. 5843 if (InsertPos) 5844 if (!RemoveNodeFromCSEMaps(N)) 5845 InsertPos = nullptr; 5846 5847 // Now we update the operands. 5848 for (unsigned i = 0; i != NumOps; ++i) 5849 if (N->OperandList[i] != Ops[i]) 5850 N->OperandList[i].set(Ops[i]); 5851 5852 // If this gets put into a CSE map, add it. 5853 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 5854 return N; 5855 } 5856 5857 /// DropOperands - Release the operands and set this node to have 5858 /// zero operands. 5859 void SDNode::DropOperands() { 5860 // Unlike the code in MorphNodeTo that does this, we don't need to 5861 // watch for dead nodes here. 5862 for (op_iterator I = op_begin(), E = op_end(); I != E; ) { 5863 SDUse &Use = *I++; 5864 Use.set(SDValue()); 5865 } 5866 } 5867 5868 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a 5869 /// machine opcode. 5870 /// 5871 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 5872 EVT VT) { 5873 SDVTList VTs = getVTList(VT); 5874 return SelectNodeTo(N, MachineOpc, VTs, None); 5875 } 5876 5877 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 5878 EVT VT, SDValue Op1) { 5879 SDVTList VTs = getVTList(VT); 5880 SDValue Ops[] = { Op1 }; 5881 return SelectNodeTo(N, MachineOpc, VTs, Ops); 5882 } 5883 5884 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 5885 EVT VT, SDValue Op1, 5886 SDValue Op2) { 5887 SDVTList VTs = getVTList(VT); 5888 SDValue Ops[] = { Op1, Op2 }; 5889 return SelectNodeTo(N, MachineOpc, VTs, Ops); 5890 } 5891 5892 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 5893 EVT VT, SDValue Op1, 5894 SDValue Op2, SDValue Op3) { 5895 SDVTList VTs = getVTList(VT); 5896 SDValue Ops[] = { Op1, Op2, Op3 }; 5897 return SelectNodeTo(N, MachineOpc, VTs, Ops); 5898 } 5899 5900 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 5901 EVT VT, ArrayRef<SDValue> Ops) { 5902 SDVTList VTs = getVTList(VT); 5903 return SelectNodeTo(N, MachineOpc, VTs, Ops); 5904 } 5905 5906 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 5907 EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) { 5908 SDVTList VTs = getVTList(VT1, VT2); 5909 return SelectNodeTo(N, MachineOpc, VTs, Ops); 5910 } 5911 5912 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 5913 EVT VT1, EVT VT2) { 5914 SDVTList VTs = getVTList(VT1, VT2); 5915 return SelectNodeTo(N, MachineOpc, VTs, None); 5916 } 5917 5918 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 5919 EVT VT1, EVT VT2, EVT VT3, 5920 ArrayRef<SDValue> Ops) { 5921 SDVTList VTs = getVTList(VT1, VT2, VT3); 5922 return SelectNodeTo(N, MachineOpc, VTs, Ops); 5923 } 5924 5925 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 5926 EVT VT1, EVT VT2, EVT VT3, EVT VT4, 5927 ArrayRef<SDValue> Ops) { 5928 SDVTList VTs = getVTList(VT1, VT2, VT3, VT4); 5929 return SelectNodeTo(N, MachineOpc, VTs, Ops); 5930 } 5931 5932 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 5933 EVT VT1, EVT VT2, 5934 SDValue Op1) { 5935 SDVTList VTs = getVTList(VT1, VT2); 5936 SDValue Ops[] = { Op1 }; 5937 return SelectNodeTo(N, MachineOpc, VTs, Ops); 5938 } 5939 5940 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 5941 EVT VT1, EVT VT2, 5942 SDValue Op1, SDValue Op2) { 5943 SDVTList VTs = getVTList(VT1, VT2); 5944 SDValue Ops[] = { Op1, Op2 }; 5945 return SelectNodeTo(N, MachineOpc, VTs, Ops); 5946 } 5947 5948 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 5949 EVT VT1, EVT VT2, 5950 SDValue Op1, SDValue Op2, 5951 SDValue Op3) { 5952 SDVTList VTs = getVTList(VT1, VT2); 5953 SDValue Ops[] = { Op1, Op2, Op3 }; 5954 return SelectNodeTo(N, MachineOpc, VTs, Ops); 5955 } 5956 5957 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 5958 EVT VT1, EVT VT2, EVT VT3, 5959 SDValue Op1, SDValue Op2, 5960 SDValue Op3) { 5961 SDVTList VTs = getVTList(VT1, VT2, VT3); 5962 SDValue Ops[] = { Op1, Op2, Op3 }; 5963 return SelectNodeTo(N, MachineOpc, VTs, Ops); 5964 } 5965 5966 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 5967 SDVTList VTs,ArrayRef<SDValue> Ops) { 5968 N = MorphNodeTo(N, ~MachineOpc, VTs, Ops); 5969 // Reset the NodeID to -1. 5970 N->setNodeId(-1); 5971 return N; 5972 } 5973 5974 /// UpdadeSDLocOnMergedSDNode - If the opt level is -O0 then it throws away 5975 /// the line number information on the merged node since it is not possible to 5976 /// preserve the information that operation is associated with multiple lines. 5977 /// This will make the debugger working better at -O0, were there is a higher 5978 /// probability having other instructions associated with that line. 5979 /// 5980 /// For IROrder, we keep the smaller of the two 5981 SDNode *SelectionDAG::UpdadeSDLocOnMergedSDNode(SDNode *N, SDLoc OLoc) { 5982 DebugLoc NLoc = N->getDebugLoc(); 5983 if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) { 5984 N->setDebugLoc(DebugLoc()); 5985 } 5986 unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder()); 5987 N->setIROrder(Order); 5988 return N; 5989 } 5990 5991 /// MorphNodeTo - This *mutates* the specified node to have the specified 5992 /// return type, opcode, and operands. 5993 /// 5994 /// Note that MorphNodeTo returns the resultant node. If there is already a 5995 /// node of the specified opcode and operands, it returns that node instead of 5996 /// the current one. Note that the SDLoc need not be the same. 5997 /// 5998 /// Using MorphNodeTo is faster than creating a new node and swapping it in 5999 /// with ReplaceAllUsesWith both because it often avoids allocating a new 6000 /// node, and because it doesn't require CSE recalculation for any of 6001 /// the node's users. 6002 /// 6003 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG. 6004 /// As a consequence it isn't appropriate to use from within the DAG combiner or 6005 /// the legalizer which maintain worklists that would need to be updated when 6006 /// deleting things. 6007 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc, 6008 SDVTList VTs, ArrayRef<SDValue> Ops) { 6009 unsigned NumOps = Ops.size(); 6010 // If an identical node already exists, use it. 6011 void *IP = nullptr; 6012 if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) { 6013 FoldingSetNodeID ID; 6014 AddNodeIDNode(ID, Opc, VTs, Ops); 6015 if (SDNode *ON = FindNodeOrInsertPos(ID, N->getDebugLoc(), IP)) 6016 return UpdadeSDLocOnMergedSDNode(ON, SDLoc(N)); 6017 } 6018 6019 if (!RemoveNodeFromCSEMaps(N)) 6020 IP = nullptr; 6021 6022 // Start the morphing. 6023 N->NodeType = Opc; 6024 N->ValueList = VTs.VTs; 6025 N->NumValues = VTs.NumVTs; 6026 6027 // Clear the operands list, updating used nodes to remove this from their 6028 // use list. Keep track of any operands that become dead as a result. 6029 SmallPtrSet<SDNode*, 16> DeadNodeSet; 6030 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) { 6031 SDUse &Use = *I++; 6032 SDNode *Used = Use.getNode(); 6033 Use.set(SDValue()); 6034 if (Used->use_empty()) 6035 DeadNodeSet.insert(Used); 6036 } 6037 6038 if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N)) { 6039 // Initialize the memory references information. 6040 MN->setMemRefs(nullptr, nullptr); 6041 // If NumOps is larger than the # of operands we can have in a 6042 // MachineSDNode, reallocate the operand list. 6043 if (NumOps > MN->NumOperands || !MN->OperandsNeedDelete) { 6044 if (MN->OperandsNeedDelete) 6045 delete[] MN->OperandList; 6046 if (NumOps > array_lengthof(MN->LocalOperands)) 6047 // We're creating a final node that will live unmorphed for the 6048 // remainder of the current SelectionDAG iteration, so we can allocate 6049 // the operands directly out of a pool with no recycling metadata. 6050 MN->InitOperands(OperandAllocator.Allocate<SDUse>(NumOps), 6051 Ops.data(), NumOps); 6052 else 6053 MN->InitOperands(MN->LocalOperands, Ops.data(), NumOps); 6054 MN->OperandsNeedDelete = false; 6055 } else 6056 MN->InitOperands(MN->OperandList, Ops.data(), NumOps); 6057 } else { 6058 // If NumOps is larger than the # of operands we currently have, reallocate 6059 // the operand list. 6060 if (NumOps > N->NumOperands) { 6061 if (N->OperandsNeedDelete) 6062 delete[] N->OperandList; 6063 N->InitOperands(new SDUse[NumOps], Ops.data(), NumOps); 6064 N->OperandsNeedDelete = true; 6065 } else 6066 N->InitOperands(N->OperandList, Ops.data(), NumOps); 6067 } 6068 6069 // Delete any nodes that are still dead after adding the uses for the 6070 // new operands. 6071 if (!DeadNodeSet.empty()) { 6072 SmallVector<SDNode *, 16> DeadNodes; 6073 for (SDNode *N : DeadNodeSet) 6074 if (N->use_empty()) 6075 DeadNodes.push_back(N); 6076 RemoveDeadNodes(DeadNodes); 6077 } 6078 6079 if (IP) 6080 CSEMap.InsertNode(N, IP); // Memoize the new node. 6081 return N; 6082 } 6083 6084 6085 /// getMachineNode - These are used for target selectors to create a new node 6086 /// with specified return type(s), MachineInstr opcode, and operands. 6087 /// 6088 /// Note that getMachineNode returns the resultant node. If there is already a 6089 /// node of the specified opcode and operands, it returns that node instead of 6090 /// the current one. 6091 MachineSDNode * 6092 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl, EVT VT) { 6093 SDVTList VTs = getVTList(VT); 6094 return getMachineNode(Opcode, dl, VTs, None); 6095 } 6096 6097 MachineSDNode * 6098 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl, EVT VT, SDValue Op1) { 6099 SDVTList VTs = getVTList(VT); 6100 SDValue Ops[] = { Op1 }; 6101 return getMachineNode(Opcode, dl, VTs, Ops); 6102 } 6103 6104 MachineSDNode * 6105 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl, EVT VT, 6106 SDValue Op1, SDValue Op2) { 6107 SDVTList VTs = getVTList(VT); 6108 SDValue Ops[] = { Op1, Op2 }; 6109 return getMachineNode(Opcode, dl, VTs, Ops); 6110 } 6111 6112 MachineSDNode * 6113 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl, EVT VT, 6114 SDValue Op1, SDValue Op2, SDValue Op3) { 6115 SDVTList VTs = getVTList(VT); 6116 SDValue Ops[] = { Op1, Op2, Op3 }; 6117 return getMachineNode(Opcode, dl, VTs, Ops); 6118 } 6119 6120 MachineSDNode * 6121 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl, EVT VT, 6122 ArrayRef<SDValue> Ops) { 6123 SDVTList VTs = getVTList(VT); 6124 return getMachineNode(Opcode, dl, VTs, Ops); 6125 } 6126 6127 MachineSDNode * 6128 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl, EVT VT1, EVT VT2) { 6129 SDVTList VTs = getVTList(VT1, VT2); 6130 return getMachineNode(Opcode, dl, VTs, None); 6131 } 6132 6133 MachineSDNode * 6134 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl, 6135 EVT VT1, EVT VT2, SDValue Op1) { 6136 SDVTList VTs = getVTList(VT1, VT2); 6137 SDValue Ops[] = { Op1 }; 6138 return getMachineNode(Opcode, dl, VTs, Ops); 6139 } 6140 6141 MachineSDNode * 6142 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl, 6143 EVT VT1, EVT VT2, SDValue Op1, SDValue Op2) { 6144 SDVTList VTs = getVTList(VT1, VT2); 6145 SDValue Ops[] = { Op1, Op2 }; 6146 return getMachineNode(Opcode, dl, VTs, Ops); 6147 } 6148 6149 MachineSDNode * 6150 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl, 6151 EVT VT1, EVT VT2, SDValue Op1, 6152 SDValue Op2, SDValue Op3) { 6153 SDVTList VTs = getVTList(VT1, VT2); 6154 SDValue Ops[] = { Op1, Op2, Op3 }; 6155 return getMachineNode(Opcode, dl, VTs, Ops); 6156 } 6157 6158 MachineSDNode * 6159 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl, 6160 EVT VT1, EVT VT2, 6161 ArrayRef<SDValue> Ops) { 6162 SDVTList VTs = getVTList(VT1, VT2); 6163 return getMachineNode(Opcode, dl, VTs, Ops); 6164 } 6165 6166 MachineSDNode * 6167 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl, 6168 EVT VT1, EVT VT2, EVT VT3, 6169 SDValue Op1, SDValue Op2) { 6170 SDVTList VTs = getVTList(VT1, VT2, VT3); 6171 SDValue Ops[] = { Op1, Op2 }; 6172 return getMachineNode(Opcode, dl, VTs, Ops); 6173 } 6174 6175 MachineSDNode * 6176 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl, 6177 EVT VT1, EVT VT2, EVT VT3, 6178 SDValue Op1, SDValue Op2, SDValue Op3) { 6179 SDVTList VTs = getVTList(VT1, VT2, VT3); 6180 SDValue Ops[] = { Op1, Op2, Op3 }; 6181 return getMachineNode(Opcode, dl, VTs, Ops); 6182 } 6183 6184 MachineSDNode * 6185 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl, 6186 EVT VT1, EVT VT2, EVT VT3, 6187 ArrayRef<SDValue> Ops) { 6188 SDVTList VTs = getVTList(VT1, VT2, VT3); 6189 return getMachineNode(Opcode, dl, VTs, Ops); 6190 } 6191 6192 MachineSDNode * 6193 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl, EVT VT1, 6194 EVT VT2, EVT VT3, EVT VT4, 6195 ArrayRef<SDValue> Ops) { 6196 SDVTList VTs = getVTList(VT1, VT2, VT3, VT4); 6197 return getMachineNode(Opcode, dl, VTs, Ops); 6198 } 6199 6200 MachineSDNode * 6201 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl, 6202 ArrayRef<EVT> ResultTys, 6203 ArrayRef<SDValue> Ops) { 6204 SDVTList VTs = getVTList(ResultTys); 6205 return getMachineNode(Opcode, dl, VTs, Ops); 6206 } 6207 6208 MachineSDNode * 6209 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc DL, SDVTList VTs, 6210 ArrayRef<SDValue> OpsArray) { 6211 bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue; 6212 MachineSDNode *N; 6213 void *IP = nullptr; 6214 const SDValue *Ops = OpsArray.data(); 6215 unsigned NumOps = OpsArray.size(); 6216 6217 if (DoCSE) { 6218 FoldingSetNodeID ID; 6219 AddNodeIDNode(ID, ~Opcode, VTs, OpsArray); 6220 IP = nullptr; 6221 if (SDNode *E = FindNodeOrInsertPos(ID, DL.getDebugLoc(), IP)) { 6222 return cast<MachineSDNode>(UpdadeSDLocOnMergedSDNode(E, DL)); 6223 } 6224 } 6225 6226 // Allocate a new MachineSDNode. 6227 N = new (NodeAllocator) MachineSDNode(~Opcode, DL.getIROrder(), 6228 DL.getDebugLoc(), VTs); 6229 6230 // Initialize the operands list. 6231 if (NumOps > array_lengthof(N->LocalOperands)) 6232 // We're creating a final node that will live unmorphed for the 6233 // remainder of the current SelectionDAG iteration, so we can allocate 6234 // the operands directly out of a pool with no recycling metadata. 6235 N->InitOperands(OperandAllocator.Allocate<SDUse>(NumOps), 6236 Ops, NumOps); 6237 else 6238 N->InitOperands(N->LocalOperands, Ops, NumOps); 6239 N->OperandsNeedDelete = false; 6240 6241 if (DoCSE) 6242 CSEMap.InsertNode(N, IP); 6243 6244 InsertNode(N); 6245 return N; 6246 } 6247 6248 /// getTargetExtractSubreg - A convenience function for creating 6249 /// TargetOpcode::EXTRACT_SUBREG nodes. 6250 SDValue 6251 SelectionDAG::getTargetExtractSubreg(int SRIdx, SDLoc DL, EVT VT, 6252 SDValue Operand) { 6253 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32); 6254 SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, 6255 VT, Operand, SRIdxVal); 6256 return SDValue(Subreg, 0); 6257 } 6258 6259 /// getTargetInsertSubreg - A convenience function for creating 6260 /// TargetOpcode::INSERT_SUBREG nodes. 6261 SDValue 6262 SelectionDAG::getTargetInsertSubreg(int SRIdx, SDLoc DL, EVT VT, 6263 SDValue Operand, SDValue Subreg) { 6264 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32); 6265 SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL, 6266 VT, Operand, Subreg, SRIdxVal); 6267 return SDValue(Result, 0); 6268 } 6269 6270 /// getNodeIfExists - Get the specified node if it's already available, or 6271 /// else return NULL. 6272 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList, 6273 ArrayRef<SDValue> Ops, 6274 const SDNodeFlags *Flags) { 6275 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) { 6276 FoldingSetNodeID ID; 6277 AddNodeIDNode(ID, Opcode, VTList, Ops); 6278 void *IP = nullptr; 6279 if (SDNode *E = FindNodeOrInsertPos(ID, DebugLoc(), IP)) { 6280 if (Flags) 6281 E->intersectFlagsWith(Flags); 6282 return E; 6283 } 6284 } 6285 return nullptr; 6286 } 6287 6288 /// getDbgValue - Creates a SDDbgValue node. 6289 /// 6290 /// SDNode 6291 SDDbgValue *SelectionDAG::getDbgValue(MDNode *Var, MDNode *Expr, SDNode *N, 6292 unsigned R, bool IsIndirect, uint64_t Off, 6293 DebugLoc DL, unsigned O) { 6294 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 6295 "Expected inlined-at fields to agree"); 6296 return new (DbgInfo->getAlloc()) 6297 SDDbgValue(Var, Expr, N, R, IsIndirect, Off, DL, O); 6298 } 6299 6300 /// Constant 6301 SDDbgValue *SelectionDAG::getConstantDbgValue(MDNode *Var, MDNode *Expr, 6302 const Value *C, uint64_t Off, 6303 DebugLoc DL, unsigned O) { 6304 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 6305 "Expected inlined-at fields to agree"); 6306 return new (DbgInfo->getAlloc()) SDDbgValue(Var, Expr, C, Off, DL, O); 6307 } 6308 6309 /// FrameIndex 6310 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(MDNode *Var, MDNode *Expr, 6311 unsigned FI, uint64_t Off, 6312 DebugLoc DL, unsigned O) { 6313 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 6314 "Expected inlined-at fields to agree"); 6315 return new (DbgInfo->getAlloc()) SDDbgValue(Var, Expr, FI, Off, DL, O); 6316 } 6317 6318 namespace { 6319 6320 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node 6321 /// pointed to by a use iterator is deleted, increment the use iterator 6322 /// so that it doesn't dangle. 6323 /// 6324 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener { 6325 SDNode::use_iterator &UI; 6326 SDNode::use_iterator &UE; 6327 6328 void NodeDeleted(SDNode *N, SDNode *E) override { 6329 // Increment the iterator as needed. 6330 while (UI != UE && N == *UI) 6331 ++UI; 6332 } 6333 6334 public: 6335 RAUWUpdateListener(SelectionDAG &d, 6336 SDNode::use_iterator &ui, 6337 SDNode::use_iterator &ue) 6338 : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {} 6339 }; 6340 6341 } 6342 6343 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 6344 /// This can cause recursive merging of nodes in the DAG. 6345 /// 6346 /// This version assumes From has a single result value. 6347 /// 6348 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) { 6349 SDNode *From = FromN.getNode(); 6350 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 && 6351 "Cannot replace with this method!"); 6352 assert(From != To.getNode() && "Cannot replace uses of with self"); 6353 6354 // Iterate over all the existing uses of From. New uses will be added 6355 // to the beginning of the use list, which we avoid visiting. 6356 // This specifically avoids visiting uses of From that arise while the 6357 // replacement is happening, because any such uses would be the result 6358 // of CSE: If an existing node looks like From after one of its operands 6359 // is replaced by To, we don't want to replace of all its users with To 6360 // too. See PR3018 for more info. 6361 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 6362 RAUWUpdateListener Listener(*this, UI, UE); 6363 while (UI != UE) { 6364 SDNode *User = *UI; 6365 6366 // This node is about to morph, remove its old self from the CSE maps. 6367 RemoveNodeFromCSEMaps(User); 6368 6369 // A user can appear in a use list multiple times, and when this 6370 // happens the uses are usually next to each other in the list. 6371 // To help reduce the number of CSE recomputations, process all 6372 // the uses of this user that we can find this way. 6373 do { 6374 SDUse &Use = UI.getUse(); 6375 ++UI; 6376 Use.set(To); 6377 } while (UI != UE && *UI == User); 6378 6379 // Now that we have modified User, add it back to the CSE maps. If it 6380 // already exists there, recursively merge the results together. 6381 AddModifiedNodeToCSEMaps(User); 6382 } 6383 6384 // If we just RAUW'd the root, take note. 6385 if (FromN == getRoot()) 6386 setRoot(To); 6387 } 6388 6389 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 6390 /// This can cause recursive merging of nodes in the DAG. 6391 /// 6392 /// This version assumes that for each value of From, there is a 6393 /// corresponding value in To in the same position with the same type. 6394 /// 6395 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) { 6396 #ifndef NDEBUG 6397 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 6398 assert((!From->hasAnyUseOfValue(i) || 6399 From->getValueType(i) == To->getValueType(i)) && 6400 "Cannot use this version of ReplaceAllUsesWith!"); 6401 #endif 6402 6403 // Handle the trivial case. 6404 if (From == To) 6405 return; 6406 6407 // Iterate over just the existing users of From. See the comments in 6408 // the ReplaceAllUsesWith above. 6409 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 6410 RAUWUpdateListener Listener(*this, UI, UE); 6411 while (UI != UE) { 6412 SDNode *User = *UI; 6413 6414 // This node is about to morph, remove its old self from the CSE maps. 6415 RemoveNodeFromCSEMaps(User); 6416 6417 // A user can appear in a use list multiple times, and when this 6418 // happens the uses are usually next to each other in the list. 6419 // To help reduce the number of CSE recomputations, process all 6420 // the uses of this user that we can find this way. 6421 do { 6422 SDUse &Use = UI.getUse(); 6423 ++UI; 6424 Use.setNode(To); 6425 } while (UI != UE && *UI == User); 6426 6427 // Now that we have modified User, add it back to the CSE maps. If it 6428 // already exists there, recursively merge the results together. 6429 AddModifiedNodeToCSEMaps(User); 6430 } 6431 6432 // If we just RAUW'd the root, take note. 6433 if (From == getRoot().getNode()) 6434 setRoot(SDValue(To, getRoot().getResNo())); 6435 } 6436 6437 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 6438 /// This can cause recursive merging of nodes in the DAG. 6439 /// 6440 /// This version can replace From with any result values. To must match the 6441 /// number and types of values returned by From. 6442 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) { 6443 if (From->getNumValues() == 1) // Handle the simple case efficiently. 6444 return ReplaceAllUsesWith(SDValue(From, 0), To[0]); 6445 6446 // Iterate over just the existing users of From. See the comments in 6447 // the ReplaceAllUsesWith above. 6448 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 6449 RAUWUpdateListener Listener(*this, UI, UE); 6450 while (UI != UE) { 6451 SDNode *User = *UI; 6452 6453 // This node is about to morph, remove its old self from the CSE maps. 6454 RemoveNodeFromCSEMaps(User); 6455 6456 // A user can appear in a use list multiple times, and when this 6457 // happens the uses are usually next to each other in the list. 6458 // To help reduce the number of CSE recomputations, process all 6459 // the uses of this user that we can find this way. 6460 do { 6461 SDUse &Use = UI.getUse(); 6462 const SDValue &ToOp = To[Use.getResNo()]; 6463 ++UI; 6464 Use.set(ToOp); 6465 } while (UI != UE && *UI == User); 6466 6467 // Now that we have modified User, add it back to the CSE maps. If it 6468 // already exists there, recursively merge the results together. 6469 AddModifiedNodeToCSEMaps(User); 6470 } 6471 6472 // If we just RAUW'd the root, take note. 6473 if (From == getRoot().getNode()) 6474 setRoot(SDValue(To[getRoot().getResNo()])); 6475 } 6476 6477 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving 6478 /// uses of other values produced by From.getNode() alone. The Deleted 6479 /// vector is handled the same way as for ReplaceAllUsesWith. 6480 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){ 6481 // Handle the really simple, really trivial case efficiently. 6482 if (From == To) return; 6483 6484 // Handle the simple, trivial, case efficiently. 6485 if (From.getNode()->getNumValues() == 1) { 6486 ReplaceAllUsesWith(From, To); 6487 return; 6488 } 6489 6490 // Iterate over just the existing users of From. See the comments in 6491 // the ReplaceAllUsesWith above. 6492 SDNode::use_iterator UI = From.getNode()->use_begin(), 6493 UE = From.getNode()->use_end(); 6494 RAUWUpdateListener Listener(*this, UI, UE); 6495 while (UI != UE) { 6496 SDNode *User = *UI; 6497 bool UserRemovedFromCSEMaps = false; 6498 6499 // A user can appear in a use list multiple times, and when this 6500 // happens the uses are usually next to each other in the list. 6501 // To help reduce the number of CSE recomputations, process all 6502 // the uses of this user that we can find this way. 6503 do { 6504 SDUse &Use = UI.getUse(); 6505 6506 // Skip uses of different values from the same node. 6507 if (Use.getResNo() != From.getResNo()) { 6508 ++UI; 6509 continue; 6510 } 6511 6512 // If this node hasn't been modified yet, it's still in the CSE maps, 6513 // so remove its old self from the CSE maps. 6514 if (!UserRemovedFromCSEMaps) { 6515 RemoveNodeFromCSEMaps(User); 6516 UserRemovedFromCSEMaps = true; 6517 } 6518 6519 ++UI; 6520 Use.set(To); 6521 } while (UI != UE && *UI == User); 6522 6523 // We are iterating over all uses of the From node, so if a use 6524 // doesn't use the specific value, no changes are made. 6525 if (!UserRemovedFromCSEMaps) 6526 continue; 6527 6528 // Now that we have modified User, add it back to the CSE maps. If it 6529 // already exists there, recursively merge the results together. 6530 AddModifiedNodeToCSEMaps(User); 6531 } 6532 6533 // If we just RAUW'd the root, take note. 6534 if (From == getRoot()) 6535 setRoot(To); 6536 } 6537 6538 namespace { 6539 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith 6540 /// to record information about a use. 6541 struct UseMemo { 6542 SDNode *User; 6543 unsigned Index; 6544 SDUse *Use; 6545 }; 6546 6547 /// operator< - Sort Memos by User. 6548 bool operator<(const UseMemo &L, const UseMemo &R) { 6549 return (intptr_t)L.User < (intptr_t)R.User; 6550 } 6551 } 6552 6553 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving 6554 /// uses of other values produced by From.getNode() alone. The same value 6555 /// may appear in both the From and To list. The Deleted vector is 6556 /// handled the same way as for ReplaceAllUsesWith. 6557 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From, 6558 const SDValue *To, 6559 unsigned Num){ 6560 // Handle the simple, trivial case efficiently. 6561 if (Num == 1) 6562 return ReplaceAllUsesOfValueWith(*From, *To); 6563 6564 // Read up all the uses and make records of them. This helps 6565 // processing new uses that are introduced during the 6566 // replacement process. 6567 SmallVector<UseMemo, 4> Uses; 6568 for (unsigned i = 0; i != Num; ++i) { 6569 unsigned FromResNo = From[i].getResNo(); 6570 SDNode *FromNode = From[i].getNode(); 6571 for (SDNode::use_iterator UI = FromNode->use_begin(), 6572 E = FromNode->use_end(); UI != E; ++UI) { 6573 SDUse &Use = UI.getUse(); 6574 if (Use.getResNo() == FromResNo) { 6575 UseMemo Memo = { *UI, i, &Use }; 6576 Uses.push_back(Memo); 6577 } 6578 } 6579 } 6580 6581 // Sort the uses, so that all the uses from a given User are together. 6582 std::sort(Uses.begin(), Uses.end()); 6583 6584 for (unsigned UseIndex = 0, UseIndexEnd = Uses.size(); 6585 UseIndex != UseIndexEnd; ) { 6586 // We know that this user uses some value of From. If it is the right 6587 // value, update it. 6588 SDNode *User = Uses[UseIndex].User; 6589 6590 // This node is about to morph, remove its old self from the CSE maps. 6591 RemoveNodeFromCSEMaps(User); 6592 6593 // The Uses array is sorted, so all the uses for a given User 6594 // are next to each other in the list. 6595 // To help reduce the number of CSE recomputations, process all 6596 // the uses of this user that we can find this way. 6597 do { 6598 unsigned i = Uses[UseIndex].Index; 6599 SDUse &Use = *Uses[UseIndex].Use; 6600 ++UseIndex; 6601 6602 Use.set(To[i]); 6603 } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User); 6604 6605 // Now that we have modified User, add it back to the CSE maps. If it 6606 // already exists there, recursively merge the results together. 6607 AddModifiedNodeToCSEMaps(User); 6608 } 6609 } 6610 6611 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG 6612 /// based on their topological order. It returns the maximum id and a vector 6613 /// of the SDNodes* in assigned order by reference. 6614 unsigned SelectionDAG::AssignTopologicalOrder() { 6615 6616 unsigned DAGSize = 0; 6617 6618 // SortedPos tracks the progress of the algorithm. Nodes before it are 6619 // sorted, nodes after it are unsorted. When the algorithm completes 6620 // it is at the end of the list. 6621 allnodes_iterator SortedPos = allnodes_begin(); 6622 6623 // Visit all the nodes. Move nodes with no operands to the front of 6624 // the list immediately. Annotate nodes that do have operands with their 6625 // operand count. Before we do this, the Node Id fields of the nodes 6626 // may contain arbitrary values. After, the Node Id fields for nodes 6627 // before SortedPos will contain the topological sort index, and the 6628 // Node Id fields for nodes At SortedPos and after will contain the 6629 // count of outstanding operands. 6630 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ) { 6631 SDNode *N = &*I++; 6632 checkForCycles(N, this); 6633 unsigned Degree = N->getNumOperands(); 6634 if (Degree == 0) { 6635 // A node with no uses, add it to the result array immediately. 6636 N->setNodeId(DAGSize++); 6637 allnodes_iterator Q(N); 6638 if (Q != SortedPos) 6639 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q)); 6640 assert(SortedPos != AllNodes.end() && "Overran node list"); 6641 ++SortedPos; 6642 } else { 6643 // Temporarily use the Node Id as scratch space for the degree count. 6644 N->setNodeId(Degree); 6645 } 6646 } 6647 6648 // Visit all the nodes. As we iterate, move nodes into sorted order, 6649 // such that by the time the end is reached all nodes will be sorted. 6650 for (SDNode &Node : allnodes()) { 6651 SDNode *N = &Node; 6652 checkForCycles(N, this); 6653 // N is in sorted position, so all its uses have one less operand 6654 // that needs to be sorted. 6655 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 6656 UI != UE; ++UI) { 6657 SDNode *P = *UI; 6658 unsigned Degree = P->getNodeId(); 6659 assert(Degree != 0 && "Invalid node degree"); 6660 --Degree; 6661 if (Degree == 0) { 6662 // All of P's operands are sorted, so P may sorted now. 6663 P->setNodeId(DAGSize++); 6664 if (P->getIterator() != SortedPos) 6665 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P)); 6666 assert(SortedPos != AllNodes.end() && "Overran node list"); 6667 ++SortedPos; 6668 } else { 6669 // Update P's outstanding operand count. 6670 P->setNodeId(Degree); 6671 } 6672 } 6673 if (Node.getIterator() == SortedPos) { 6674 #ifndef NDEBUG 6675 allnodes_iterator I(N); 6676 SDNode *S = &*++I; 6677 dbgs() << "Overran sorted position:\n"; 6678 S->dumprFull(this); dbgs() << "\n"; 6679 dbgs() << "Checking if this is due to cycles\n"; 6680 checkForCycles(this, true); 6681 #endif 6682 llvm_unreachable(nullptr); 6683 } 6684 } 6685 6686 assert(SortedPos == AllNodes.end() && 6687 "Topological sort incomplete!"); 6688 assert(AllNodes.front().getOpcode() == ISD::EntryToken && 6689 "First node in topological sort is not the entry token!"); 6690 assert(AllNodes.front().getNodeId() == 0 && 6691 "First node in topological sort has non-zero id!"); 6692 assert(AllNodes.front().getNumOperands() == 0 && 6693 "First node in topological sort has operands!"); 6694 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 && 6695 "Last node in topologic sort has unexpected id!"); 6696 assert(AllNodes.back().use_empty() && 6697 "Last node in topologic sort has users!"); 6698 assert(DAGSize == allnodes_size() && "Node count mismatch!"); 6699 return DAGSize; 6700 } 6701 6702 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the 6703 /// value is produced by SD. 6704 void SelectionDAG::AddDbgValue(SDDbgValue *DB, SDNode *SD, bool isParameter) { 6705 if (SD) { 6706 assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue()); 6707 SD->setHasDebugValue(true); 6708 } 6709 DbgInfo->add(DB, SD, isParameter); 6710 } 6711 6712 /// TransferDbgValues - Transfer SDDbgValues. 6713 void SelectionDAG::TransferDbgValues(SDValue From, SDValue To) { 6714 if (From == To || !From.getNode()->getHasDebugValue()) 6715 return; 6716 SDNode *FromNode = From.getNode(); 6717 SDNode *ToNode = To.getNode(); 6718 ArrayRef<SDDbgValue *> DVs = GetDbgValues(FromNode); 6719 SmallVector<SDDbgValue *, 2> ClonedDVs; 6720 for (ArrayRef<SDDbgValue *>::iterator I = DVs.begin(), E = DVs.end(); 6721 I != E; ++I) { 6722 SDDbgValue *Dbg = *I; 6723 if (Dbg->getKind() == SDDbgValue::SDNODE) { 6724 SDDbgValue *Clone = 6725 getDbgValue(Dbg->getVariable(), Dbg->getExpression(), ToNode, 6726 To.getResNo(), Dbg->isIndirect(), Dbg->getOffset(), 6727 Dbg->getDebugLoc(), Dbg->getOrder()); 6728 ClonedDVs.push_back(Clone); 6729 } 6730 } 6731 for (SmallVectorImpl<SDDbgValue *>::iterator I = ClonedDVs.begin(), 6732 E = ClonedDVs.end(); I != E; ++I) 6733 AddDbgValue(*I, ToNode, false); 6734 } 6735 6736 //===----------------------------------------------------------------------===// 6737 // SDNode Class 6738 //===----------------------------------------------------------------------===// 6739 6740 bool llvm::isNullConstant(SDValue V) { 6741 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 6742 return Const != nullptr && Const->isNullValue(); 6743 } 6744 6745 bool llvm::isNullFPConstant(SDValue V) { 6746 ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V); 6747 return Const != nullptr && Const->isZero() && !Const->isNegative(); 6748 } 6749 6750 bool llvm::isAllOnesConstant(SDValue V) { 6751 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 6752 return Const != nullptr && Const->isAllOnesValue(); 6753 } 6754 6755 bool llvm::isOneConstant(SDValue V) { 6756 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 6757 return Const != nullptr && Const->isOne(); 6758 } 6759 6760 HandleSDNode::~HandleSDNode() { 6761 DropOperands(); 6762 } 6763 6764 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order, 6765 DebugLoc DL, const GlobalValue *GA, 6766 EVT VT, int64_t o, unsigned char TF) 6767 : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) { 6768 TheGlobal = GA; 6769 } 6770 6771 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, DebugLoc dl, EVT VT, 6772 SDValue X, unsigned SrcAS, 6773 unsigned DestAS) 6774 : UnarySDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT), X), 6775 SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {} 6776 6777 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, DebugLoc dl, SDVTList VTs, 6778 EVT memvt, MachineMemOperand *mmo) 6779 : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) { 6780 SubclassData = encodeMemSDNodeFlags(0, ISD::UNINDEXED, MMO->isVolatile(), 6781 MMO->isNonTemporal(), MMO->isInvariant()); 6782 assert(isVolatile() == MMO->isVolatile() && "Volatile encoding error!"); 6783 assert(isNonTemporal() == MMO->isNonTemporal() && 6784 "Non-temporal encoding error!"); 6785 // We check here that the size of the memory operand fits within the size of 6786 // the MMO. This is because the MMO might indicate only a possible address 6787 // range instead of specifying the affected memory addresses precisely. 6788 assert(memvt.getStoreSize() <= MMO->getSize() && "Size mismatch!"); 6789 } 6790 6791 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, DebugLoc dl, SDVTList VTs, 6792 ArrayRef<SDValue> Ops, EVT memvt, MachineMemOperand *mmo) 6793 : SDNode(Opc, Order, dl, VTs, Ops), 6794 MemoryVT(memvt), MMO(mmo) { 6795 SubclassData = encodeMemSDNodeFlags(0, ISD::UNINDEXED, MMO->isVolatile(), 6796 MMO->isNonTemporal(), MMO->isInvariant()); 6797 assert(isVolatile() == MMO->isVolatile() && "Volatile encoding error!"); 6798 assert(memvt.getStoreSize() <= MMO->getSize() && "Size mismatch!"); 6799 } 6800 6801 /// Profile - Gather unique data for the node. 6802 /// 6803 void SDNode::Profile(FoldingSetNodeID &ID) const { 6804 AddNodeIDNode(ID, this); 6805 } 6806 6807 namespace { 6808 struct EVTArray { 6809 std::vector<EVT> VTs; 6810 6811 EVTArray() { 6812 VTs.reserve(MVT::LAST_VALUETYPE); 6813 for (unsigned i = 0; i < MVT::LAST_VALUETYPE; ++i) 6814 VTs.push_back(MVT((MVT::SimpleValueType)i)); 6815 } 6816 }; 6817 } 6818 6819 static ManagedStatic<std::set<EVT, EVT::compareRawBits> > EVTs; 6820 static ManagedStatic<EVTArray> SimpleVTArray; 6821 static ManagedStatic<sys::SmartMutex<true> > VTMutex; 6822 6823 /// getValueTypeList - Return a pointer to the specified value type. 6824 /// 6825 const EVT *SDNode::getValueTypeList(EVT VT) { 6826 if (VT.isExtended()) { 6827 sys::SmartScopedLock<true> Lock(*VTMutex); 6828 return &(*EVTs->insert(VT).first); 6829 } else { 6830 assert(VT.getSimpleVT() < MVT::LAST_VALUETYPE && 6831 "Value type out of range!"); 6832 return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy]; 6833 } 6834 } 6835 6836 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the 6837 /// indicated value. This method ignores uses of other values defined by this 6838 /// operation. 6839 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const { 6840 assert(Value < getNumValues() && "Bad value!"); 6841 6842 // TODO: Only iterate over uses of a given value of the node 6843 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) { 6844 if (UI.getUse().getResNo() == Value) { 6845 if (NUses == 0) 6846 return false; 6847 --NUses; 6848 } 6849 } 6850 6851 // Found exactly the right number of uses? 6852 return NUses == 0; 6853 } 6854 6855 6856 /// hasAnyUseOfValue - Return true if there are any use of the indicated 6857 /// value. This method ignores uses of other values defined by this operation. 6858 bool SDNode::hasAnyUseOfValue(unsigned Value) const { 6859 assert(Value < getNumValues() && "Bad value!"); 6860 6861 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) 6862 if (UI.getUse().getResNo() == Value) 6863 return true; 6864 6865 return false; 6866 } 6867 6868 6869 /// isOnlyUserOf - Return true if this node is the only use of N. 6870 /// 6871 bool SDNode::isOnlyUserOf(const SDNode *N) const { 6872 bool Seen = false; 6873 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) { 6874 SDNode *User = *I; 6875 if (User == this) 6876 Seen = true; 6877 else 6878 return false; 6879 } 6880 6881 return Seen; 6882 } 6883 6884 /// isOperand - Return true if this node is an operand of N. 6885 /// 6886 bool SDValue::isOperandOf(const SDNode *N) const { 6887 for (const SDValue &Op : N->op_values()) 6888 if (*this == Op) 6889 return true; 6890 return false; 6891 } 6892 6893 bool SDNode::isOperandOf(const SDNode *N) const { 6894 for (const SDValue &Op : N->op_values()) 6895 if (this == Op.getNode()) 6896 return true; 6897 return false; 6898 } 6899 6900 /// reachesChainWithoutSideEffects - Return true if this operand (which must 6901 /// be a chain) reaches the specified operand without crossing any 6902 /// side-effecting instructions on any chain path. In practice, this looks 6903 /// through token factors and non-volatile loads. In order to remain efficient, 6904 /// this only looks a couple of nodes in, it does not do an exhaustive search. 6905 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest, 6906 unsigned Depth) const { 6907 if (*this == Dest) return true; 6908 6909 // Don't search too deeply, we just want to be able to see through 6910 // TokenFactor's etc. 6911 if (Depth == 0) return false; 6912 6913 // If this is a token factor, all inputs to the TF happen in parallel. If any 6914 // of the operands of the TF does not reach dest, then we cannot do the xform. 6915 if (getOpcode() == ISD::TokenFactor) { 6916 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) 6917 if (!getOperand(i).reachesChainWithoutSideEffects(Dest, Depth-1)) 6918 return false; 6919 return true; 6920 } 6921 6922 // Loads don't have side effects, look through them. 6923 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) { 6924 if (!Ld->isVolatile()) 6925 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1); 6926 } 6927 return false; 6928 } 6929 6930 /// hasPredecessor - Return true if N is a predecessor of this node. 6931 /// N is either an operand of this node, or can be reached by recursively 6932 /// traversing up the operands. 6933 /// NOTE: This is an expensive method. Use it carefully. 6934 bool SDNode::hasPredecessor(const SDNode *N) const { 6935 SmallPtrSet<const SDNode *, 32> Visited; 6936 SmallVector<const SDNode *, 16> Worklist; 6937 return hasPredecessorHelper(N, Visited, Worklist); 6938 } 6939 6940 bool 6941 SDNode::hasPredecessorHelper(const SDNode *N, 6942 SmallPtrSetImpl<const SDNode *> &Visited, 6943 SmallVectorImpl<const SDNode *> &Worklist) const { 6944 if (Visited.empty()) { 6945 Worklist.push_back(this); 6946 } else { 6947 // Take a look in the visited set. If we've already encountered this node 6948 // we needn't search further. 6949 if (Visited.count(N)) 6950 return true; 6951 } 6952 6953 // Haven't visited N yet. Continue the search. 6954 while (!Worklist.empty()) { 6955 const SDNode *M = Worklist.pop_back_val(); 6956 bool Found = false; 6957 for (const SDValue &OpV : M->op_values()) { 6958 SDNode *Op = OpV.getNode(); 6959 if (Visited.insert(Op).second) 6960 Worklist.push_back(Op); 6961 if (Op == N) 6962 Found = true; 6963 } 6964 if (Found) 6965 return true; 6966 } 6967 6968 return false; 6969 } 6970 6971 uint64_t SDNode::getConstantOperandVal(unsigned Num) const { 6972 assert(Num < NumOperands && "Invalid child # of SDNode!"); 6973 return cast<ConstantSDNode>(OperandList[Num])->getZExtValue(); 6974 } 6975 6976 const SDNodeFlags *SDNode::getFlags() const { 6977 if (auto *FlagsNode = dyn_cast<BinaryWithFlagsSDNode>(this)) 6978 return &FlagsNode->Flags; 6979 return nullptr; 6980 } 6981 6982 void SDNode::intersectFlagsWith(const SDNodeFlags *Flags) { 6983 if (auto *FlagsNode = dyn_cast<BinaryWithFlagsSDNode>(this)) 6984 FlagsNode->Flags.intersectWith(Flags); 6985 } 6986 6987 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) { 6988 assert(N->getNumValues() == 1 && 6989 "Can't unroll a vector with multiple results!"); 6990 6991 EVT VT = N->getValueType(0); 6992 unsigned NE = VT.getVectorNumElements(); 6993 EVT EltVT = VT.getVectorElementType(); 6994 SDLoc dl(N); 6995 6996 SmallVector<SDValue, 8> Scalars; 6997 SmallVector<SDValue, 4> Operands(N->getNumOperands()); 6998 6999 // If ResNE is 0, fully unroll the vector op. 7000 if (ResNE == 0) 7001 ResNE = NE; 7002 else if (NE > ResNE) 7003 NE = ResNE; 7004 7005 unsigned i; 7006 for (i= 0; i != NE; ++i) { 7007 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) { 7008 SDValue Operand = N->getOperand(j); 7009 EVT OperandVT = Operand.getValueType(); 7010 if (OperandVT.isVector()) { 7011 // A vector operand; extract a single element. 7012 EVT OperandEltVT = OperandVT.getVectorElementType(); 7013 Operands[j] = 7014 getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT, Operand, 7015 getConstant(i, dl, TLI->getVectorIdxTy(getDataLayout()))); 7016 } else { 7017 // A scalar operand; just use it as is. 7018 Operands[j] = Operand; 7019 } 7020 } 7021 7022 switch (N->getOpcode()) { 7023 default: { 7024 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands, 7025 N->getFlags())); 7026 break; 7027 } 7028 case ISD::VSELECT: 7029 Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands)); 7030 break; 7031 case ISD::SHL: 7032 case ISD::SRA: 7033 case ISD::SRL: 7034 case ISD::ROTL: 7035 case ISD::ROTR: 7036 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0], 7037 getShiftAmountOperand(Operands[0].getValueType(), 7038 Operands[1]))); 7039 break; 7040 case ISD::SIGN_EXTEND_INREG: 7041 case ISD::FP_ROUND_INREG: { 7042 EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType(); 7043 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, 7044 Operands[0], 7045 getValueType(ExtVT))); 7046 } 7047 } 7048 } 7049 7050 for (; i < ResNE; ++i) 7051 Scalars.push_back(getUNDEF(EltVT)); 7052 7053 return getNode(ISD::BUILD_VECTOR, dl, 7054 EVT::getVectorVT(*getContext(), EltVT, ResNE), Scalars); 7055 } 7056 7057 7058 /// isConsecutiveLoad - Return true if LD is loading 'Bytes' bytes from a 7059 /// location that is 'Dist' units away from the location that the 'Base' load 7060 /// is loading from. 7061 bool SelectionDAG::isConsecutiveLoad(LoadSDNode *LD, LoadSDNode *Base, 7062 unsigned Bytes, int Dist) const { 7063 if (LD->getChain() != Base->getChain()) 7064 return false; 7065 EVT VT = LD->getValueType(0); 7066 if (VT.getSizeInBits() / 8 != Bytes) 7067 return false; 7068 7069 SDValue Loc = LD->getOperand(1); 7070 SDValue BaseLoc = Base->getOperand(1); 7071 if (Loc.getOpcode() == ISD::FrameIndex) { 7072 if (BaseLoc.getOpcode() != ISD::FrameIndex) 7073 return false; 7074 const MachineFrameInfo *MFI = getMachineFunction().getFrameInfo(); 7075 int FI = cast<FrameIndexSDNode>(Loc)->getIndex(); 7076 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex(); 7077 int FS = MFI->getObjectSize(FI); 7078 int BFS = MFI->getObjectSize(BFI); 7079 if (FS != BFS || FS != (int)Bytes) return false; 7080 return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Bytes); 7081 } 7082 7083 // Handle X + C. 7084 if (isBaseWithConstantOffset(Loc)) { 7085 int64_t LocOffset = cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue(); 7086 if (Loc.getOperand(0) == BaseLoc) { 7087 // If the base location is a simple address with no offset itself, then 7088 // the second load's first add operand should be the base address. 7089 if (LocOffset == Dist * (int)Bytes) 7090 return true; 7091 } else if (isBaseWithConstantOffset(BaseLoc)) { 7092 // The base location itself has an offset, so subtract that value from the 7093 // second load's offset before comparing to distance * size. 7094 int64_t BOffset = 7095 cast<ConstantSDNode>(BaseLoc.getOperand(1))->getSExtValue(); 7096 if (Loc.getOperand(0) == BaseLoc.getOperand(0)) { 7097 if ((LocOffset - BOffset) == Dist * (int)Bytes) 7098 return true; 7099 } 7100 } 7101 } 7102 const GlobalValue *GV1 = nullptr; 7103 const GlobalValue *GV2 = nullptr; 7104 int64_t Offset1 = 0; 7105 int64_t Offset2 = 0; 7106 bool isGA1 = TLI->isGAPlusOffset(Loc.getNode(), GV1, Offset1); 7107 bool isGA2 = TLI->isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2); 7108 if (isGA1 && isGA2 && GV1 == GV2) 7109 return Offset1 == (Offset2 + Dist*Bytes); 7110 return false; 7111 } 7112 7113 7114 /// InferPtrAlignment - Infer alignment of a load / store address. Return 0 if 7115 /// it cannot be inferred. 7116 unsigned SelectionDAG::InferPtrAlignment(SDValue Ptr) const { 7117 // If this is a GlobalAddress + cst, return the alignment. 7118 const GlobalValue *GV; 7119 int64_t GVOffset = 0; 7120 if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) { 7121 unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType()); 7122 APInt KnownZero(PtrWidth, 0), KnownOne(PtrWidth, 0); 7123 llvm::computeKnownBits(const_cast<GlobalValue *>(GV), KnownZero, KnownOne, 7124 getDataLayout()); 7125 unsigned AlignBits = KnownZero.countTrailingOnes(); 7126 unsigned Align = AlignBits ? 1 << std::min(31U, AlignBits) : 0; 7127 if (Align) 7128 return MinAlign(Align, GVOffset); 7129 } 7130 7131 // If this is a direct reference to a stack slot, use information about the 7132 // stack slot's alignment. 7133 int FrameIdx = 1 << 31; 7134 int64_t FrameOffset = 0; 7135 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) { 7136 FrameIdx = FI->getIndex(); 7137 } else if (isBaseWithConstantOffset(Ptr) && 7138 isa<FrameIndexSDNode>(Ptr.getOperand(0))) { 7139 // Handle FI+Cst 7140 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex(); 7141 FrameOffset = Ptr.getConstantOperandVal(1); 7142 } 7143 7144 if (FrameIdx != (1 << 31)) { 7145 const MachineFrameInfo &MFI = *getMachineFunction().getFrameInfo(); 7146 unsigned FIInfoAlign = MinAlign(MFI.getObjectAlignment(FrameIdx), 7147 FrameOffset); 7148 return FIInfoAlign; 7149 } 7150 7151 return 0; 7152 } 7153 7154 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type 7155 /// which is split (or expanded) into two not necessarily identical pieces. 7156 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const { 7157 // Currently all types are split in half. 7158 EVT LoVT, HiVT; 7159 if (!VT.isVector()) { 7160 LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT); 7161 } else { 7162 unsigned NumElements = VT.getVectorNumElements(); 7163 assert(!(NumElements & 1) && "Splitting vector, but not in half!"); 7164 LoVT = HiVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(), 7165 NumElements/2); 7166 } 7167 return std::make_pair(LoVT, HiVT); 7168 } 7169 7170 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the 7171 /// low/high part. 7172 std::pair<SDValue, SDValue> 7173 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT, 7174 const EVT &HiVT) { 7175 assert(LoVT.getVectorNumElements() + HiVT.getVectorNumElements() <= 7176 N.getValueType().getVectorNumElements() && 7177 "More vector elements requested than available!"); 7178 SDValue Lo, Hi; 7179 Lo = getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N, 7180 getConstant(0, DL, TLI->getVectorIdxTy(getDataLayout()))); 7181 Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N, 7182 getConstant(LoVT.getVectorNumElements(), DL, 7183 TLI->getVectorIdxTy(getDataLayout()))); 7184 return std::make_pair(Lo, Hi); 7185 } 7186 7187 void SelectionDAG::ExtractVectorElements(SDValue Op, 7188 SmallVectorImpl<SDValue> &Args, 7189 unsigned Start, unsigned Count) { 7190 EVT VT = Op.getValueType(); 7191 if (Count == 0) 7192 Count = VT.getVectorNumElements(); 7193 7194 EVT EltVT = VT.getVectorElementType(); 7195 EVT IdxTy = TLI->getVectorIdxTy(getDataLayout()); 7196 SDLoc SL(Op); 7197 for (unsigned i = Start, e = Start + Count; i != e; ++i) { 7198 Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 7199 Op, getConstant(i, SL, IdxTy))); 7200 } 7201 } 7202 7203 // getAddressSpace - Return the address space this GlobalAddress belongs to. 7204 unsigned GlobalAddressSDNode::getAddressSpace() const { 7205 return getGlobal()->getType()->getAddressSpace(); 7206 } 7207 7208 7209 Type *ConstantPoolSDNode::getType() const { 7210 if (isMachineConstantPoolEntry()) 7211 return Val.MachineCPVal->getType(); 7212 return Val.ConstVal->getType(); 7213 } 7214 7215 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, 7216 APInt &SplatUndef, 7217 unsigned &SplatBitSize, 7218 bool &HasAnyUndefs, 7219 unsigned MinSplatBits, 7220 bool isBigEndian) const { 7221 EVT VT = getValueType(0); 7222 assert(VT.isVector() && "Expected a vector type"); 7223 unsigned sz = VT.getSizeInBits(); 7224 if (MinSplatBits > sz) 7225 return false; 7226 7227 SplatValue = APInt(sz, 0); 7228 SplatUndef = APInt(sz, 0); 7229 7230 // Get the bits. Bits with undefined values (when the corresponding element 7231 // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared 7232 // in SplatValue. If any of the values are not constant, give up and return 7233 // false. 7234 unsigned int nOps = getNumOperands(); 7235 assert(nOps > 0 && "isConstantSplat has 0-size build vector"); 7236 unsigned EltBitSize = VT.getVectorElementType().getSizeInBits(); 7237 7238 for (unsigned j = 0; j < nOps; ++j) { 7239 unsigned i = isBigEndian ? nOps-1-j : j; 7240 SDValue OpVal = getOperand(i); 7241 unsigned BitPos = j * EltBitSize; 7242 7243 if (OpVal.getOpcode() == ISD::UNDEF) 7244 SplatUndef |= APInt::getBitsSet(sz, BitPos, BitPos + EltBitSize); 7245 else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) 7246 SplatValue |= CN->getAPIntValue().zextOrTrunc(EltBitSize). 7247 zextOrTrunc(sz) << BitPos; 7248 else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) 7249 SplatValue |= CN->getValueAPF().bitcastToAPInt().zextOrTrunc(sz) <<BitPos; 7250 else 7251 return false; 7252 } 7253 7254 // The build_vector is all constants or undefs. Find the smallest element 7255 // size that splats the vector. 7256 7257 HasAnyUndefs = (SplatUndef != 0); 7258 while (sz > 8) { 7259 7260 unsigned HalfSize = sz / 2; 7261 APInt HighValue = SplatValue.lshr(HalfSize).trunc(HalfSize); 7262 APInt LowValue = SplatValue.trunc(HalfSize); 7263 APInt HighUndef = SplatUndef.lshr(HalfSize).trunc(HalfSize); 7264 APInt LowUndef = SplatUndef.trunc(HalfSize); 7265 7266 // If the two halves do not match (ignoring undef bits), stop here. 7267 if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) || 7268 MinSplatBits > HalfSize) 7269 break; 7270 7271 SplatValue = HighValue | LowValue; 7272 SplatUndef = HighUndef & LowUndef; 7273 7274 sz = HalfSize; 7275 } 7276 7277 SplatBitSize = sz; 7278 return true; 7279 } 7280 7281 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const { 7282 if (UndefElements) { 7283 UndefElements->clear(); 7284 UndefElements->resize(getNumOperands()); 7285 } 7286 SDValue Splatted; 7287 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) { 7288 SDValue Op = getOperand(i); 7289 if (Op.getOpcode() == ISD::UNDEF) { 7290 if (UndefElements) 7291 (*UndefElements)[i] = true; 7292 } else if (!Splatted) { 7293 Splatted = Op; 7294 } else if (Splatted != Op) { 7295 return SDValue(); 7296 } 7297 } 7298 7299 if (!Splatted) { 7300 assert(getOperand(0).getOpcode() == ISD::UNDEF && 7301 "Can only have a splat without a constant for all undefs."); 7302 return getOperand(0); 7303 } 7304 7305 return Splatted; 7306 } 7307 7308 ConstantSDNode * 7309 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const { 7310 return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements)); 7311 } 7312 7313 ConstantFPSDNode * 7314 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const { 7315 return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements)); 7316 } 7317 7318 int32_t 7319 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements, 7320 uint32_t BitWidth) const { 7321 if (ConstantFPSDNode *CN = 7322 dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) { 7323 bool IsExact; 7324 APSInt IntVal(BitWidth); 7325 APFloat APF = CN->getValueAPF(); 7326 if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) != 7327 APFloat::opOK || 7328 !IsExact) 7329 return -1; 7330 7331 return IntVal.exactLogBase2(); 7332 } 7333 return -1; 7334 } 7335 7336 bool BuildVectorSDNode::isConstant() const { 7337 for (const SDValue &Op : op_values()) { 7338 unsigned Opc = Op.getOpcode(); 7339 if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP) 7340 return false; 7341 } 7342 return true; 7343 } 7344 7345 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) { 7346 // Find the first non-undef value in the shuffle mask. 7347 unsigned i, e; 7348 for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i) 7349 /* search */; 7350 7351 assert(i != e && "VECTOR_SHUFFLE node with all undef indices!"); 7352 7353 // Make sure all remaining elements are either undef or the same as the first 7354 // non-undef value. 7355 for (int Idx = Mask[i]; i != e; ++i) 7356 if (Mask[i] >= 0 && Mask[i] != Idx) 7357 return false; 7358 return true; 7359 } 7360 7361 // \brief Returns the SDNode if it is a constant integer BuildVector 7362 // or constant integer. 7363 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) { 7364 if (isa<ConstantSDNode>(N)) 7365 return N.getNode(); 7366 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode())) 7367 return N.getNode(); 7368 // Treat a GlobalAddress supporting constant offset folding as a 7369 // constant integer. 7370 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N)) 7371 if (GA->getOpcode() == ISD::GlobalAddress && 7372 TLI->isOffsetFoldingLegal(GA)) 7373 return GA; 7374 return nullptr; 7375 } 7376 7377 #ifndef NDEBUG 7378 static void checkForCyclesHelper(const SDNode *N, 7379 SmallPtrSetImpl<const SDNode*> &Visited, 7380 SmallPtrSetImpl<const SDNode*> &Checked, 7381 const llvm::SelectionDAG *DAG) { 7382 // If this node has already been checked, don't check it again. 7383 if (Checked.count(N)) 7384 return; 7385 7386 // If a node has already been visited on this depth-first walk, reject it as 7387 // a cycle. 7388 if (!Visited.insert(N).second) { 7389 errs() << "Detected cycle in SelectionDAG\n"; 7390 dbgs() << "Offending node:\n"; 7391 N->dumprFull(DAG); dbgs() << "\n"; 7392 abort(); 7393 } 7394 7395 for (const SDValue &Op : N->op_values()) 7396 checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG); 7397 7398 Checked.insert(N); 7399 Visited.erase(N); 7400 } 7401 #endif 7402 7403 void llvm::checkForCycles(const llvm::SDNode *N, 7404 const llvm::SelectionDAG *DAG, 7405 bool force) { 7406 #ifndef NDEBUG 7407 bool check = force; 7408 #ifdef XDEBUG 7409 check = true; 7410 #endif // XDEBUG 7411 if (check) { 7412 assert(N && "Checking nonexistent SDNode"); 7413 SmallPtrSet<const SDNode*, 32> visited; 7414 SmallPtrSet<const SDNode*, 32> checked; 7415 checkForCyclesHelper(N, visited, checked, DAG); 7416 } 7417 #endif // !NDEBUG 7418 } 7419 7420 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) { 7421 checkForCycles(DAG->getRoot().getNode(), DAG, force); 7422 } 7423