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