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