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