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