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