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