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 "SDNodeDbgValue.h" 16 #include "llvm/ADT/SetVector.h" 17 #include "llvm/ADT/SmallPtrSet.h" 18 #include "llvm/ADT/SmallSet.h" 19 #include "llvm/ADT/SmallVector.h" 20 #include "llvm/ADT/StringExtras.h" 21 #include "llvm/Analysis/TargetTransformInfo.h" 22 #include "llvm/Analysis/ValueTracking.h" 23 #include "llvm/Assembly/Writer.h" 24 #include "llvm/CodeGen/MachineBasicBlock.h" 25 #include "llvm/CodeGen/MachineConstantPool.h" 26 #include "llvm/CodeGen/MachineFrameInfo.h" 27 #include "llvm/CodeGen/MachineModuleInfo.h" 28 #include "llvm/DebugInfo.h" 29 #include "llvm/IR/CallingConv.h" 30 #include "llvm/IR/Constants.h" 31 #include "llvm/IR/DataLayout.h" 32 #include "llvm/IR/DerivedTypes.h" 33 #include "llvm/IR/Function.h" 34 #include "llvm/IR/GlobalAlias.h" 35 #include "llvm/IR/GlobalVariable.h" 36 #include "llvm/IR/Intrinsics.h" 37 #include "llvm/Support/CommandLine.h" 38 #include "llvm/Support/Debug.h" 39 #include "llvm/Support/ErrorHandling.h" 40 #include "llvm/Support/ManagedStatic.h" 41 #include "llvm/Support/MathExtras.h" 42 #include "llvm/Support/Mutex.h" 43 #include "llvm/Support/raw_ostream.h" 44 #include "llvm/Target/TargetInstrInfo.h" 45 #include "llvm/Target/TargetIntrinsicInfo.h" 46 #include "llvm/Target/TargetLowering.h" 47 #include "llvm/Target/TargetMachine.h" 48 #include "llvm/Target/TargetOptions.h" 49 #include "llvm/Target/TargetRegisterInfo.h" 50 #include "llvm/Target/TargetSelectionDAGInfo.h" 51 #include <algorithm> 52 #include <cmath> 53 using namespace llvm; 54 55 /// makeVTList - Return an instance of the SDVTList struct initialized with the 56 /// specified members. 57 static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) { 58 SDVTList Res = {VTs, NumVTs}; 59 return Res; 60 } 61 62 // Default null implementations of the callbacks. 63 void SelectionDAG::DAGUpdateListener::NodeDeleted(SDNode*, SDNode*) {} 64 void SelectionDAG::DAGUpdateListener::NodeUpdated(SDNode*) {} 65 66 //===----------------------------------------------------------------------===// 67 // ConstantFPSDNode Class 68 //===----------------------------------------------------------------------===// 69 70 /// isExactlyValue - We don't rely on operator== working on double values, as 71 /// it returns true for things that are clearly not equal, like -0.0 and 0.0. 72 /// As such, this method can be used to do an exact bit-for-bit comparison of 73 /// two floating point values. 74 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const { 75 return getValueAPF().bitwiseIsEqual(V); 76 } 77 78 bool ConstantFPSDNode::isValueValidForType(EVT VT, 79 const APFloat& Val) { 80 assert(VT.isFloatingPoint() && "Can only convert between FP types"); 81 82 // convert modifies in place, so make a copy. 83 APFloat Val2 = APFloat(Val); 84 bool losesInfo; 85 (void) Val2.convert(SelectionDAG::EVTToAPFloatSemantics(VT), 86 APFloat::rmNearestTiesToEven, 87 &losesInfo); 88 return !losesInfo; 89 } 90 91 //===----------------------------------------------------------------------===// 92 // ISD Namespace 93 //===----------------------------------------------------------------------===// 94 95 /// isBuildVectorAllOnes - Return true if the specified node is a 96 /// BUILD_VECTOR where all of the elements are ~0 or undef. 97 bool ISD::isBuildVectorAllOnes(const SDNode *N) { 98 // Look through a bit convert. 99 if (N->getOpcode() == ISD::BITCAST) 100 N = N->getOperand(0).getNode(); 101 102 if (N->getOpcode() != ISD::BUILD_VECTOR) return false; 103 104 unsigned i = 0, e = N->getNumOperands(); 105 106 // Skip over all of the undef values. 107 while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF) 108 ++i; 109 110 // Do not accept an all-undef vector. 111 if (i == e) return false; 112 113 // Do not accept build_vectors that aren't all constants or which have non-~0 114 // elements. We have to be a bit careful here, as the type of the constant 115 // may not be the same as the type of the vector elements due to type 116 // legalization (the elements are promoted to a legal type for the target and 117 // a vector of a type may be legal when the base element type is not). 118 // We only want to check enough bits to cover the vector elements, because 119 // we care if the resultant vector is all ones, not whether the individual 120 // constants are. 121 SDValue NotZero = N->getOperand(i); 122 unsigned EltSize = N->getValueType(0).getVectorElementType().getSizeInBits(); 123 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(NotZero)) { 124 if (CN->getAPIntValue().countTrailingOnes() < EltSize) 125 return false; 126 } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(NotZero)) { 127 if (CFPN->getValueAPF().bitcastToAPInt().countTrailingOnes() < EltSize) 128 return false; 129 } else 130 return false; 131 132 // Okay, we have at least one ~0 value, check to see if the rest match or are 133 // undefs. Even with the above element type twiddling, this should be OK, as 134 // the same type legalization should have applied to all the elements. 135 for (++i; i != e; ++i) 136 if (N->getOperand(i) != NotZero && 137 N->getOperand(i).getOpcode() != ISD::UNDEF) 138 return false; 139 return true; 140 } 141 142 143 /// isBuildVectorAllZeros - Return true if the specified node is a 144 /// BUILD_VECTOR where all of the elements are 0 or undef. 145 bool ISD::isBuildVectorAllZeros(const SDNode *N) { 146 // Look through a bit convert. 147 if (N->getOpcode() == ISD::BITCAST) 148 N = N->getOperand(0).getNode(); 149 150 if (N->getOpcode() != ISD::BUILD_VECTOR) return false; 151 152 unsigned i = 0, e = N->getNumOperands(); 153 154 // Skip over all of the undef values. 155 while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF) 156 ++i; 157 158 // Do not accept an all-undef vector. 159 if (i == e) return false; 160 161 // Do not accept build_vectors that aren't all constants or which have non-0 162 // elements. 163 SDValue Zero = N->getOperand(i); 164 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Zero)) { 165 if (!CN->isNullValue()) 166 return false; 167 } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(Zero)) { 168 if (!CFPN->getValueAPF().isPosZero()) 169 return false; 170 } else 171 return false; 172 173 // Okay, we have at least one 0 value, check to see if the rest match or are 174 // undefs. 175 for (++i; i != e; ++i) 176 if (N->getOperand(i) != Zero && 177 N->getOperand(i).getOpcode() != ISD::UNDEF) 178 return false; 179 return true; 180 } 181 182 /// isScalarToVector - Return true if the specified node is a 183 /// ISD::SCALAR_TO_VECTOR node or a BUILD_VECTOR node where only the low 184 /// element is not an undef. 185 bool ISD::isScalarToVector(const SDNode *N) { 186 if (N->getOpcode() == ISD::SCALAR_TO_VECTOR) 187 return true; 188 189 if (N->getOpcode() != ISD::BUILD_VECTOR) 190 return false; 191 if (N->getOperand(0).getOpcode() == ISD::UNDEF) 192 return false; 193 unsigned NumElems = N->getNumOperands(); 194 if (NumElems == 1) 195 return false; 196 for (unsigned i = 1; i < NumElems; ++i) { 197 SDValue V = N->getOperand(i); 198 if (V.getOpcode() != ISD::UNDEF) 199 return false; 200 } 201 return true; 202 } 203 204 /// allOperandsUndef - Return true if the node has at least one operand 205 /// and all operands of the specified node are ISD::UNDEF. 206 bool ISD::allOperandsUndef(const SDNode *N) { 207 // Return false if the node has no operands. 208 // This is "logically inconsistent" with the definition of "all" but 209 // is probably the desired behavior. 210 if (N->getNumOperands() == 0) 211 return false; 212 213 for (unsigned i = 0, e = N->getNumOperands(); i != e ; ++i) 214 if (N->getOperand(i).getOpcode() != ISD::UNDEF) 215 return false; 216 217 return true; 218 } 219 220 /// getSetCCSwappedOperands - Return the operation corresponding to (Y op X) 221 /// when given the operation for (X op Y). 222 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) { 223 // To perform this operation, we just need to swap the L and G bits of the 224 // operation. 225 unsigned OldL = (Operation >> 2) & 1; 226 unsigned OldG = (Operation >> 1) & 1; 227 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits 228 (OldL << 1) | // New G bit 229 (OldG << 2)); // New L bit. 230 } 231 232 /// getSetCCInverse - Return the operation corresponding to !(X op Y), where 233 /// 'op' is a valid SetCC operation. 234 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, bool isInteger) { 235 unsigned Operation = Op; 236 if (isInteger) 237 Operation ^= 7; // Flip L, G, E bits, but not U. 238 else 239 Operation ^= 15; // Flip all of the condition bits. 240 241 if (Operation > ISD::SETTRUE2) 242 Operation &= ~8; // Don't let N and U bits get set. 243 244 return ISD::CondCode(Operation); 245 } 246 247 248 /// isSignedOp - For an integer comparison, return 1 if the comparison is a 249 /// signed operation and 2 if the result is an unsigned comparison. Return zero 250 /// if the operation does not depend on the sign of the input (setne and seteq). 251 static int isSignedOp(ISD::CondCode Opcode) { 252 switch (Opcode) { 253 default: llvm_unreachable("Illegal integer setcc operation!"); 254 case ISD::SETEQ: 255 case ISD::SETNE: return 0; 256 case ISD::SETLT: 257 case ISD::SETLE: 258 case ISD::SETGT: 259 case ISD::SETGE: return 1; 260 case ISD::SETULT: 261 case ISD::SETULE: 262 case ISD::SETUGT: 263 case ISD::SETUGE: return 2; 264 } 265 } 266 267 /// getSetCCOrOperation - Return the result of a logical OR between different 268 /// comparisons of identical values: ((X op1 Y) | (X op2 Y)). This function 269 /// returns SETCC_INVALID if it is not possible to represent the resultant 270 /// comparison. 271 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2, 272 bool isInteger) { 273 if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3) 274 // Cannot fold a signed integer setcc with an unsigned integer setcc. 275 return ISD::SETCC_INVALID; 276 277 unsigned Op = Op1 | Op2; // Combine all of the condition bits. 278 279 // If the N and U bits get set then the resultant comparison DOES suddenly 280 // care about orderedness, and is true when ordered. 281 if (Op > ISD::SETTRUE2) 282 Op &= ~16; // Clear the U bit if the N bit is set. 283 284 // Canonicalize illegal integer setcc's. 285 if (isInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT 286 Op = ISD::SETNE; 287 288 return ISD::CondCode(Op); 289 } 290 291 /// getSetCCAndOperation - Return the result of a logical AND between different 292 /// comparisons of identical values: ((X op1 Y) & (X op2 Y)). This 293 /// function returns zero if it is not possible to represent the resultant 294 /// comparison. 295 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2, 296 bool isInteger) { 297 if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3) 298 // Cannot fold a signed setcc with an unsigned setcc. 299 return ISD::SETCC_INVALID; 300 301 // Combine all of the condition bits. 302 ISD::CondCode Result = ISD::CondCode(Op1 & Op2); 303 304 // Canonicalize illegal integer setcc's. 305 if (isInteger) { 306 switch (Result) { 307 default: break; 308 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT 309 case ISD::SETOEQ: // SETEQ & SETU[LG]E 310 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE 311 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE 312 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE 313 } 314 } 315 316 return Result; 317 } 318 319 //===----------------------------------------------------------------------===// 320 // SDNode Profile Support 321 //===----------------------------------------------------------------------===// 322 323 /// AddNodeIDOpcode - Add the node opcode to the NodeID data. 324 /// 325 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) { 326 ID.AddInteger(OpC); 327 } 328 329 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them 330 /// solely with their pointer. 331 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) { 332 ID.AddPointer(VTList.VTs); 333 } 334 335 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data. 336 /// 337 static void AddNodeIDOperands(FoldingSetNodeID &ID, 338 const SDValue *Ops, unsigned NumOps) { 339 for (; NumOps; --NumOps, ++Ops) { 340 ID.AddPointer(Ops->getNode()); 341 ID.AddInteger(Ops->getResNo()); 342 } 343 } 344 345 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data. 346 /// 347 static void AddNodeIDOperands(FoldingSetNodeID &ID, 348 const SDUse *Ops, unsigned NumOps) { 349 for (; NumOps; --NumOps, ++Ops) { 350 ID.AddPointer(Ops->getNode()); 351 ID.AddInteger(Ops->getResNo()); 352 } 353 } 354 355 static void AddNodeIDNode(FoldingSetNodeID &ID, 356 unsigned short OpC, SDVTList VTList, 357 const SDValue *OpList, unsigned N) { 358 AddNodeIDOpcode(ID, OpC); 359 AddNodeIDValueTypes(ID, VTList); 360 AddNodeIDOperands(ID, OpList, N); 361 } 362 363 /// AddNodeIDCustom - If this is an SDNode with special info, add this info to 364 /// the NodeID data. 365 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) { 366 switch (N->getOpcode()) { 367 case ISD::TargetExternalSymbol: 368 case ISD::ExternalSymbol: 369 llvm_unreachable("Should only be used on nodes with operands"); 370 default: break; // Normal nodes don't need extra info. 371 case ISD::TargetConstant: 372 case ISD::Constant: 373 ID.AddPointer(cast<ConstantSDNode>(N)->getConstantIntValue()); 374 break; 375 case ISD::TargetConstantFP: 376 case ISD::ConstantFP: { 377 ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue()); 378 break; 379 } 380 case ISD::TargetGlobalAddress: 381 case ISD::GlobalAddress: 382 case ISD::TargetGlobalTLSAddress: 383 case ISD::GlobalTLSAddress: { 384 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N); 385 ID.AddPointer(GA->getGlobal()); 386 ID.AddInteger(GA->getOffset()); 387 ID.AddInteger(GA->getTargetFlags()); 388 ID.AddInteger(GA->getAddressSpace()); 389 break; 390 } 391 case ISD::BasicBlock: 392 ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock()); 393 break; 394 case ISD::Register: 395 ID.AddInteger(cast<RegisterSDNode>(N)->getReg()); 396 break; 397 case ISD::RegisterMask: 398 ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask()); 399 break; 400 case ISD::SRCVALUE: 401 ID.AddPointer(cast<SrcValueSDNode>(N)->getValue()); 402 break; 403 case ISD::FrameIndex: 404 case ISD::TargetFrameIndex: 405 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex()); 406 break; 407 case ISD::JumpTable: 408 case ISD::TargetJumpTable: 409 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex()); 410 ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags()); 411 break; 412 case ISD::ConstantPool: 413 case ISD::TargetConstantPool: { 414 const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N); 415 ID.AddInteger(CP->getAlignment()); 416 ID.AddInteger(CP->getOffset()); 417 if (CP->isMachineConstantPoolEntry()) 418 CP->getMachineCPVal()->addSelectionDAGCSEId(ID); 419 else 420 ID.AddPointer(CP->getConstVal()); 421 ID.AddInteger(CP->getTargetFlags()); 422 break; 423 } 424 case ISD::TargetIndex: { 425 const TargetIndexSDNode *TI = cast<TargetIndexSDNode>(N); 426 ID.AddInteger(TI->getIndex()); 427 ID.AddInteger(TI->getOffset()); 428 ID.AddInteger(TI->getTargetFlags()); 429 break; 430 } 431 case ISD::LOAD: { 432 const LoadSDNode *LD = cast<LoadSDNode>(N); 433 ID.AddInteger(LD->getMemoryVT().getRawBits()); 434 ID.AddInteger(LD->getRawSubclassData()); 435 ID.AddInteger(LD->getPointerInfo().getAddrSpace()); 436 break; 437 } 438 case ISD::STORE: { 439 const StoreSDNode *ST = cast<StoreSDNode>(N); 440 ID.AddInteger(ST->getMemoryVT().getRawBits()); 441 ID.AddInteger(ST->getRawSubclassData()); 442 ID.AddInteger(ST->getPointerInfo().getAddrSpace()); 443 break; 444 } 445 case ISD::ATOMIC_CMP_SWAP: 446 case ISD::ATOMIC_SWAP: 447 case ISD::ATOMIC_LOAD_ADD: 448 case ISD::ATOMIC_LOAD_SUB: 449 case ISD::ATOMIC_LOAD_AND: 450 case ISD::ATOMIC_LOAD_OR: 451 case ISD::ATOMIC_LOAD_XOR: 452 case ISD::ATOMIC_LOAD_NAND: 453 case ISD::ATOMIC_LOAD_MIN: 454 case ISD::ATOMIC_LOAD_MAX: 455 case ISD::ATOMIC_LOAD_UMIN: 456 case ISD::ATOMIC_LOAD_UMAX: 457 case ISD::ATOMIC_LOAD: 458 case ISD::ATOMIC_STORE: { 459 const AtomicSDNode *AT = cast<AtomicSDNode>(N); 460 ID.AddInteger(AT->getMemoryVT().getRawBits()); 461 ID.AddInteger(AT->getRawSubclassData()); 462 ID.AddInteger(AT->getPointerInfo().getAddrSpace()); 463 break; 464 } 465 case ISD::PREFETCH: { 466 const MemSDNode *PF = cast<MemSDNode>(N); 467 ID.AddInteger(PF->getPointerInfo().getAddrSpace()); 468 break; 469 } 470 case ISD::VECTOR_SHUFFLE: { 471 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 472 for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements(); 473 i != e; ++i) 474 ID.AddInteger(SVN->getMaskElt(i)); 475 break; 476 } 477 case ISD::TargetBlockAddress: 478 case ISD::BlockAddress: { 479 const BlockAddressSDNode *BA = cast<BlockAddressSDNode>(N); 480 ID.AddPointer(BA->getBlockAddress()); 481 ID.AddInteger(BA->getOffset()); 482 ID.AddInteger(BA->getTargetFlags()); 483 break; 484 } 485 } // end switch (N->getOpcode()) 486 487 // Target specific memory nodes could also have address spaces to check. 488 if (N->isTargetMemoryOpcode()) 489 ID.AddInteger(cast<MemSDNode>(N)->getPointerInfo().getAddrSpace()); 490 } 491 492 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID 493 /// data. 494 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) { 495 AddNodeIDOpcode(ID, N->getOpcode()); 496 // Add the return value info. 497 AddNodeIDValueTypes(ID, N->getVTList()); 498 // Add the operand info. 499 AddNodeIDOperands(ID, N->op_begin(), N->getNumOperands()); 500 501 // Handle SDNode leafs with special info. 502 AddNodeIDCustom(ID, N); 503 } 504 505 /// encodeMemSDNodeFlags - Generic routine for computing a value for use in 506 /// the CSE map that carries volatility, temporalness, indexing mode, and 507 /// extension/truncation information. 508 /// 509 static inline unsigned 510 encodeMemSDNodeFlags(int ConvType, ISD::MemIndexedMode AM, bool isVolatile, 511 bool isNonTemporal, bool isInvariant) { 512 assert((ConvType & 3) == ConvType && 513 "ConvType may not require more than 2 bits!"); 514 assert((AM & 7) == AM && 515 "AM may not require more than 3 bits!"); 516 return ConvType | 517 (AM << 2) | 518 (isVolatile << 5) | 519 (isNonTemporal << 6) | 520 (isInvariant << 7); 521 } 522 523 //===----------------------------------------------------------------------===// 524 // SelectionDAG Class 525 //===----------------------------------------------------------------------===// 526 527 /// doNotCSE - Return true if CSE should not be performed for this node. 528 static bool doNotCSE(SDNode *N) { 529 if (N->getValueType(0) == MVT::Glue) 530 return true; // Never CSE anything that produces a flag. 531 532 switch (N->getOpcode()) { 533 default: break; 534 case ISD::HANDLENODE: 535 case ISD::EH_LABEL: 536 return true; // Never CSE these nodes. 537 } 538 539 // Check that remaining values produced are not flags. 540 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i) 541 if (N->getValueType(i) == MVT::Glue) 542 return true; // Never CSE anything that produces a flag. 543 544 return false; 545 } 546 547 /// RemoveDeadNodes - This method deletes all unreachable nodes in the 548 /// SelectionDAG. 549 void SelectionDAG::RemoveDeadNodes() { 550 // Create a dummy node (which is not added to allnodes), that adds a reference 551 // to the root node, preventing it from being deleted. 552 HandleSDNode Dummy(getRoot()); 553 554 SmallVector<SDNode*, 128> DeadNodes; 555 556 // Add all obviously-dead nodes to the DeadNodes worklist. 557 for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I) 558 if (I->use_empty()) 559 DeadNodes.push_back(I); 560 561 RemoveDeadNodes(DeadNodes); 562 563 // If the root changed (e.g. it was a dead load, update the root). 564 setRoot(Dummy.getValue()); 565 } 566 567 /// RemoveDeadNodes - This method deletes the unreachable nodes in the 568 /// given list, and any nodes that become unreachable as a result. 569 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes) { 570 571 // Process the worklist, deleting the nodes and adding their uses to the 572 // worklist. 573 while (!DeadNodes.empty()) { 574 SDNode *N = DeadNodes.pop_back_val(); 575 576 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 577 DUL->NodeDeleted(N, 0); 578 579 // Take the node out of the appropriate CSE map. 580 RemoveNodeFromCSEMaps(N); 581 582 // Next, brutally remove the operand list. This is safe to do, as there are 583 // no cycles in the graph. 584 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) { 585 SDUse &Use = *I++; 586 SDNode *Operand = Use.getNode(); 587 Use.set(SDValue()); 588 589 // Now that we removed this operand, see if there are no uses of it left. 590 if (Operand->use_empty()) 591 DeadNodes.push_back(Operand); 592 } 593 594 DeallocateNode(N); 595 } 596 } 597 598 void SelectionDAG::RemoveDeadNode(SDNode *N){ 599 SmallVector<SDNode*, 16> DeadNodes(1, N); 600 601 // Create a dummy node that adds a reference to the root node, preventing 602 // it from being deleted. (This matters if the root is an operand of the 603 // dead node.) 604 HandleSDNode Dummy(getRoot()); 605 606 RemoveDeadNodes(DeadNodes); 607 } 608 609 void SelectionDAG::DeleteNode(SDNode *N) { 610 // First take this out of the appropriate CSE map. 611 RemoveNodeFromCSEMaps(N); 612 613 // Finally, remove uses due to operands of this node, remove from the 614 // AllNodes list, and delete the node. 615 DeleteNodeNotInCSEMaps(N); 616 } 617 618 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) { 619 assert(N != AllNodes.begin() && "Cannot delete the entry node!"); 620 assert(N->use_empty() && "Cannot delete a node that is not dead!"); 621 622 // Drop all of the operands and decrement used node's use counts. 623 N->DropOperands(); 624 625 DeallocateNode(N); 626 } 627 628 void SelectionDAG::DeallocateNode(SDNode *N) { 629 if (N->OperandsNeedDelete) 630 delete[] N->OperandList; 631 632 // Set the opcode to DELETED_NODE to help catch bugs when node 633 // memory is reallocated. 634 N->NodeType = ISD::DELETED_NODE; 635 636 NodeAllocator.Deallocate(AllNodes.remove(N)); 637 638 // If any of the SDDbgValue nodes refer to this SDNode, invalidate them. 639 ArrayRef<SDDbgValue*> DbgVals = DbgInfo->getSDDbgValues(N); 640 for (unsigned i = 0, e = DbgVals.size(); i != e; ++i) 641 DbgVals[i]->setIsInvalidated(); 642 } 643 644 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that 645 /// correspond to it. This is useful when we're about to delete or repurpose 646 /// the node. We don't want future request for structurally identical nodes 647 /// to return N anymore. 648 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) { 649 bool Erased = false; 650 switch (N->getOpcode()) { 651 case ISD::HANDLENODE: return false; // noop. 652 case ISD::CONDCODE: 653 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] && 654 "Cond code doesn't exist!"); 655 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != 0; 656 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = 0; 657 break; 658 case ISD::ExternalSymbol: 659 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol()); 660 break; 661 case ISD::TargetExternalSymbol: { 662 ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N); 663 Erased = TargetExternalSymbols.erase( 664 std::pair<std::string,unsigned char>(ESN->getSymbol(), 665 ESN->getTargetFlags())); 666 break; 667 } 668 case ISD::VALUETYPE: { 669 EVT VT = cast<VTSDNode>(N)->getVT(); 670 if (VT.isExtended()) { 671 Erased = ExtendedValueTypeNodes.erase(VT); 672 } else { 673 Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != 0; 674 ValueTypeNodes[VT.getSimpleVT().SimpleTy] = 0; 675 } 676 break; 677 } 678 default: 679 // Remove it from the CSE Map. 680 assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!"); 681 assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!"); 682 Erased = CSEMap.RemoveNode(N); 683 break; 684 } 685 #ifndef NDEBUG 686 // Verify that the node was actually in one of the CSE maps, unless it has a 687 // flag result (which cannot be CSE'd) or is one of the special cases that are 688 // not subject to CSE. 689 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue && 690 !N->isMachineOpcode() && !doNotCSE(N)) { 691 N->dump(this); 692 dbgs() << "\n"; 693 llvm_unreachable("Node is not in map!"); 694 } 695 #endif 696 return Erased; 697 } 698 699 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE 700 /// maps and modified in place. Add it back to the CSE maps, unless an identical 701 /// node already exists, in which case transfer all its users to the existing 702 /// node. This transfer can potentially trigger recursive merging. 703 /// 704 void 705 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) { 706 // For node types that aren't CSE'd, just act as if no identical node 707 // already exists. 708 if (!doNotCSE(N)) { 709 SDNode *Existing = CSEMap.GetOrInsertNode(N); 710 if (Existing != N) { 711 // If there was already an existing matching node, use ReplaceAllUsesWith 712 // to replace the dead one with the existing one. This can cause 713 // recursive merging of other unrelated nodes down the line. 714 ReplaceAllUsesWith(N, Existing); 715 716 // N is now dead. Inform the listeners and delete it. 717 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 718 DUL->NodeDeleted(N, Existing); 719 DeleteNodeNotInCSEMaps(N); 720 return; 721 } 722 } 723 724 // If the node doesn't already exist, we updated it. Inform listeners. 725 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 726 DUL->NodeUpdated(N); 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. 733 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op, 734 void *&InsertPos) { 735 if (doNotCSE(N)) 736 return 0; 737 738 SDValue Ops[] = { Op }; 739 FoldingSetNodeID ID; 740 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 1); 741 AddNodeIDCustom(ID, N); 742 SDNode *Node = CSEMap.FindNodeOrInsertPos(ID, InsertPos); 743 return Node; 744 } 745 746 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands 747 /// were replaced with those specified. If this node is never memoized, 748 /// return null, otherwise return a pointer to the slot it would take. If a 749 /// node already exists with these operands, the slot will be non-null. 750 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, 751 SDValue Op1, SDValue Op2, 752 void *&InsertPos) { 753 if (doNotCSE(N)) 754 return 0; 755 756 SDValue Ops[] = { Op1, Op2 }; 757 FoldingSetNodeID ID; 758 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 2); 759 AddNodeIDCustom(ID, N); 760 SDNode *Node = CSEMap.FindNodeOrInsertPos(ID, InsertPos); 761 return Node; 762 } 763 764 765 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands 766 /// were replaced with those specified. If this node is never memoized, 767 /// return null, otherwise return a pointer to the slot it would take. If a 768 /// node already exists with these operands, the slot will be non-null. 769 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, 770 const SDValue *Ops,unsigned NumOps, 771 void *&InsertPos) { 772 if (doNotCSE(N)) 773 return 0; 774 775 FoldingSetNodeID ID; 776 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, NumOps); 777 AddNodeIDCustom(ID, N); 778 SDNode *Node = CSEMap.FindNodeOrInsertPos(ID, InsertPos); 779 return Node; 780 } 781 782 #ifndef NDEBUG 783 /// VerifyNodeCommon - Sanity check the given node. Aborts if it is invalid. 784 static void VerifyNodeCommon(SDNode *N) { 785 switch (N->getOpcode()) { 786 default: 787 break; 788 case ISD::BUILD_PAIR: { 789 EVT VT = N->getValueType(0); 790 assert(N->getNumValues() == 1 && "Too many results!"); 791 assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) && 792 "Wrong return type!"); 793 assert(N->getNumOperands() == 2 && "Wrong number of operands!"); 794 assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() && 795 "Mismatched operand types!"); 796 assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() && 797 "Wrong operand type!"); 798 assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() && 799 "Wrong return type size"); 800 break; 801 } 802 case ISD::BUILD_VECTOR: { 803 assert(N->getNumValues() == 1 && "Too many results!"); 804 assert(N->getValueType(0).isVector() && "Wrong return type!"); 805 assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() && 806 "Wrong number of operands!"); 807 EVT EltVT = N->getValueType(0).getVectorElementType(); 808 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) { 809 assert((I->getValueType() == EltVT || 810 (EltVT.isInteger() && I->getValueType().isInteger() && 811 EltVT.bitsLE(I->getValueType()))) && 812 "Wrong operand type!"); 813 assert(I->getValueType() == N->getOperand(0).getValueType() && 814 "Operands must all have the same type"); 815 } 816 break; 817 } 818 } 819 } 820 821 /// VerifySDNode - Sanity check the given SDNode. Aborts if it is invalid. 822 static void VerifySDNode(SDNode *N) { 823 // The SDNode allocators cannot be used to allocate nodes with fields that are 824 // not present in an SDNode! 825 assert(!isa<MemSDNode>(N) && "Bad MemSDNode!"); 826 assert(!isa<ShuffleVectorSDNode>(N) && "Bad ShuffleVectorSDNode!"); 827 assert(!isa<ConstantSDNode>(N) && "Bad ConstantSDNode!"); 828 assert(!isa<ConstantFPSDNode>(N) && "Bad ConstantFPSDNode!"); 829 assert(!isa<GlobalAddressSDNode>(N) && "Bad GlobalAddressSDNode!"); 830 assert(!isa<FrameIndexSDNode>(N) && "Bad FrameIndexSDNode!"); 831 assert(!isa<JumpTableSDNode>(N) && "Bad JumpTableSDNode!"); 832 assert(!isa<ConstantPoolSDNode>(N) && "Bad ConstantPoolSDNode!"); 833 assert(!isa<BasicBlockSDNode>(N) && "Bad BasicBlockSDNode!"); 834 assert(!isa<SrcValueSDNode>(N) && "Bad SrcValueSDNode!"); 835 assert(!isa<MDNodeSDNode>(N) && "Bad MDNodeSDNode!"); 836 assert(!isa<RegisterSDNode>(N) && "Bad RegisterSDNode!"); 837 assert(!isa<BlockAddressSDNode>(N) && "Bad BlockAddressSDNode!"); 838 assert(!isa<EHLabelSDNode>(N) && "Bad EHLabelSDNode!"); 839 assert(!isa<ExternalSymbolSDNode>(N) && "Bad ExternalSymbolSDNode!"); 840 assert(!isa<CondCodeSDNode>(N) && "Bad CondCodeSDNode!"); 841 assert(!isa<CvtRndSatSDNode>(N) && "Bad CvtRndSatSDNode!"); 842 assert(!isa<VTSDNode>(N) && "Bad VTSDNode!"); 843 assert(!isa<MachineSDNode>(N) && "Bad MachineSDNode!"); 844 845 VerifyNodeCommon(N); 846 } 847 848 /// VerifyMachineNode - Sanity check the given MachineNode. Aborts if it is 849 /// invalid. 850 static void VerifyMachineNode(SDNode *N) { 851 // The MachineNode allocators cannot be used to allocate nodes with fields 852 // that are not present in a MachineNode! 853 // Currently there are no such nodes. 854 855 VerifyNodeCommon(N); 856 } 857 #endif // NDEBUG 858 859 /// getEVTAlignment - Compute the default alignment value for the 860 /// given type. 861 /// 862 unsigned SelectionDAG::getEVTAlignment(EVT VT) const { 863 Type *Ty = VT == MVT::iPTR ? 864 PointerType::get(Type::getInt8Ty(*getContext()), 0) : 865 VT.getTypeForEVT(*getContext()); 866 867 return TM.getTargetLowering()->getDataLayout()->getABITypeAlignment(Ty); 868 } 869 870 // EntryNode could meaningfully have debug info if we can find it... 871 SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL) 872 : TM(tm), TSI(*tm.getSelectionDAGInfo()), TTI(0), OptLevel(OL), 873 EntryNode(ISD::EntryToken, 0, DebugLoc(), getVTList(MVT::Other)), 874 Root(getEntryNode()), UpdateListeners(0) { 875 AllNodes.push_back(&EntryNode); 876 DbgInfo = new SDDbgInfo(); 877 } 878 879 void SelectionDAG::init(MachineFunction &mf, const TargetTransformInfo *tti) { 880 MF = &mf; 881 TTI = tti; 882 Context = &mf.getFunction()->getContext(); 883 } 884 885 SelectionDAG::~SelectionDAG() { 886 assert(!UpdateListeners && "Dangling registered DAGUpdateListeners"); 887 allnodes_clear(); 888 delete DbgInfo; 889 } 890 891 void SelectionDAG::allnodes_clear() { 892 assert(&*AllNodes.begin() == &EntryNode); 893 AllNodes.remove(AllNodes.begin()); 894 while (!AllNodes.empty()) 895 DeallocateNode(AllNodes.begin()); 896 } 897 898 void SelectionDAG::clear() { 899 allnodes_clear(); 900 OperandAllocator.Reset(); 901 CSEMap.clear(); 902 903 ExtendedValueTypeNodes.clear(); 904 ExternalSymbols.clear(); 905 TargetExternalSymbols.clear(); 906 std::fill(CondCodeNodes.begin(), CondCodeNodes.end(), 907 static_cast<CondCodeSDNode*>(0)); 908 std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(), 909 static_cast<SDNode*>(0)); 910 911 EntryNode.UseList = 0; 912 AllNodes.push_back(&EntryNode); 913 Root = getEntryNode(); 914 DbgInfo->clear(); 915 } 916 917 SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, SDLoc DL, EVT VT) { 918 return VT.bitsGT(Op.getValueType()) ? 919 getNode(ISD::ANY_EXTEND, DL, VT, Op) : 920 getNode(ISD::TRUNCATE, DL, VT, Op); 921 } 922 923 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, SDLoc DL, EVT VT) { 924 return VT.bitsGT(Op.getValueType()) ? 925 getNode(ISD::SIGN_EXTEND, DL, VT, Op) : 926 getNode(ISD::TRUNCATE, DL, VT, Op); 927 } 928 929 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, SDLoc DL, EVT VT) { 930 return VT.bitsGT(Op.getValueType()) ? 931 getNode(ISD::ZERO_EXTEND, DL, VT, Op) : 932 getNode(ISD::TRUNCATE, DL, VT, Op); 933 } 934 935 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, SDLoc DL, EVT VT) { 936 assert(!VT.isVector() && 937 "getZeroExtendInReg should use the vector element type instead of " 938 "the vector type!"); 939 if (Op.getValueType() == VT) return Op; 940 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits(); 941 APInt Imm = APInt::getLowBitsSet(BitWidth, 942 VT.getSizeInBits()); 943 return getNode(ISD::AND, DL, Op.getValueType(), Op, 944 getConstant(Imm, Op.getValueType())); 945 } 946 947 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1). 948 /// 949 SDValue SelectionDAG::getNOT(SDLoc DL, SDValue Val, EVT VT) { 950 EVT EltVT = VT.getScalarType(); 951 SDValue NegOne = 952 getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT); 953 return getNode(ISD::XOR, DL, VT, Val, NegOne); 954 } 955 956 SDValue SelectionDAG::getConstant(uint64_t Val, EVT VT, bool isT) { 957 EVT EltVT = VT.getScalarType(); 958 assert((EltVT.getSizeInBits() >= 64 || 959 (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) && 960 "getConstant with a uint64_t value that doesn't fit in the type!"); 961 return getConstant(APInt(EltVT.getSizeInBits(), Val), VT, isT); 962 } 963 964 SDValue SelectionDAG::getConstant(const APInt &Val, EVT VT, bool isT) { 965 return getConstant(*ConstantInt::get(*Context, Val), VT, isT); 966 } 967 968 SDValue SelectionDAG::getConstant(const ConstantInt &Val, EVT VT, bool isT) { 969 assert(VT.isInteger() && "Cannot create FP integer constant!"); 970 971 EVT EltVT = VT.getScalarType(); 972 const ConstantInt *Elt = &Val; 973 974 const TargetLowering *TLI = TM.getTargetLowering(); 975 976 // In some cases the vector type is legal but the element type is illegal and 977 // needs to be promoted, for example v8i8 on ARM. In this case, promote the 978 // inserted value (the type does not need to match the vector element type). 979 // Any extra bits introduced will be truncated away. 980 if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) == 981 TargetLowering::TypePromoteInteger) { 982 EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT); 983 APInt NewVal = Elt->getValue().zext(EltVT.getSizeInBits()); 984 Elt = ConstantInt::get(*getContext(), NewVal); 985 } 986 987 assert(Elt->getBitWidth() == EltVT.getSizeInBits() && 988 "APInt size does not match type size!"); 989 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant; 990 FoldingSetNodeID ID; 991 AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0); 992 ID.AddPointer(Elt); 993 void *IP = 0; 994 SDNode *N = NULL; 995 if ((N = CSEMap.FindNodeOrInsertPos(ID, IP))) 996 if (!VT.isVector()) 997 return SDValue(N, 0); 998 999 if (!N) { 1000 N = new (NodeAllocator) ConstantSDNode(isT, Elt, EltVT); 1001 CSEMap.InsertNode(N, IP); 1002 AllNodes.push_back(N); 1003 } 1004 1005 SDValue Result(N, 0); 1006 if (VT.isVector()) { 1007 SmallVector<SDValue, 8> Ops; 1008 Ops.assign(VT.getVectorNumElements(), Result); 1009 Result = getNode(ISD::BUILD_VECTOR, SDLoc(), VT, &Ops[0], Ops.size()); 1010 } 1011 return Result; 1012 } 1013 1014 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, bool isTarget) { 1015 return getConstant(Val, TM.getTargetLowering()->getPointerTy(), isTarget); 1016 } 1017 1018 1019 SDValue SelectionDAG::getConstantFP(const APFloat& V, EVT VT, bool isTarget) { 1020 return getConstantFP(*ConstantFP::get(*getContext(), V), VT, isTarget); 1021 } 1022 1023 SDValue SelectionDAG::getConstantFP(const ConstantFP& V, EVT VT, bool isTarget){ 1024 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!"); 1025 1026 EVT EltVT = VT.getScalarType(); 1027 1028 // Do the map lookup using the actual bit pattern for the floating point 1029 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and 1030 // we don't have issues with SNANs. 1031 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP; 1032 FoldingSetNodeID ID; 1033 AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0); 1034 ID.AddPointer(&V); 1035 void *IP = 0; 1036 SDNode *N = NULL; 1037 if ((N = CSEMap.FindNodeOrInsertPos(ID, IP))) 1038 if (!VT.isVector()) 1039 return SDValue(N, 0); 1040 1041 if (!N) { 1042 N = new (NodeAllocator) ConstantFPSDNode(isTarget, &V, EltVT); 1043 CSEMap.InsertNode(N, IP); 1044 AllNodes.push_back(N); 1045 } 1046 1047 SDValue Result(N, 0); 1048 if (VT.isVector()) { 1049 SmallVector<SDValue, 8> Ops; 1050 Ops.assign(VT.getVectorNumElements(), Result); 1051 // FIXME SDLoc info might be appropriate here 1052 Result = getNode(ISD::BUILD_VECTOR, SDLoc(), VT, &Ops[0], Ops.size()); 1053 } 1054 return Result; 1055 } 1056 1057 SDValue SelectionDAG::getConstantFP(double Val, EVT VT, bool isTarget) { 1058 EVT EltVT = VT.getScalarType(); 1059 if (EltVT==MVT::f32) 1060 return getConstantFP(APFloat((float)Val), VT, isTarget); 1061 else if (EltVT==MVT::f64) 1062 return getConstantFP(APFloat(Val), VT, isTarget); 1063 else if (EltVT==MVT::f80 || EltVT==MVT::f128 || EltVT==MVT::ppcf128 || 1064 EltVT==MVT::f16) { 1065 bool ignored; 1066 APFloat apf = APFloat(Val); 1067 apf.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven, 1068 &ignored); 1069 return getConstantFP(apf, VT, isTarget); 1070 } else 1071 llvm_unreachable("Unsupported type in getConstantFP"); 1072 } 1073 1074 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, SDLoc DL, 1075 EVT VT, int64_t Offset, 1076 bool isTargetGA, 1077 unsigned char TargetFlags) { 1078 assert((TargetFlags == 0 || isTargetGA) && 1079 "Cannot set target flags on target-independent globals"); 1080 1081 // Truncate (with sign-extension) the offset value to the pointer size. 1082 unsigned BitWidth = TM.getTargetLowering()->getPointerTy().getSizeInBits(); 1083 if (BitWidth < 64) 1084 Offset = SignExtend64(Offset, BitWidth); 1085 1086 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV); 1087 if (!GVar) { 1088 // If GV is an alias then use the aliasee for determining thread-localness. 1089 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV)) 1090 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal(false)); 1091 } 1092 1093 unsigned Opc; 1094 if (GVar && GVar->isThreadLocal()) 1095 Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress; 1096 else 1097 Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress; 1098 1099 FoldingSetNodeID ID; 1100 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0); 1101 ID.AddPointer(GV); 1102 ID.AddInteger(Offset); 1103 ID.AddInteger(TargetFlags); 1104 ID.AddInteger(GV->getType()->getAddressSpace()); 1105 void *IP = 0; 1106 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) 1107 return SDValue(E, 0); 1108 1109 SDNode *N = new (NodeAllocator) GlobalAddressSDNode(Opc, DL.getIROrder(), 1110 DL.getDebugLoc(), GV, VT, 1111 Offset, TargetFlags); 1112 CSEMap.InsertNode(N, IP); 1113 AllNodes.push_back(N); 1114 return SDValue(N, 0); 1115 } 1116 1117 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) { 1118 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex; 1119 FoldingSetNodeID ID; 1120 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0); 1121 ID.AddInteger(FI); 1122 void *IP = 0; 1123 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) 1124 return SDValue(E, 0); 1125 1126 SDNode *N = new (NodeAllocator) FrameIndexSDNode(FI, VT, isTarget); 1127 CSEMap.InsertNode(N, IP); 1128 AllNodes.push_back(N); 1129 return SDValue(N, 0); 1130 } 1131 1132 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget, 1133 unsigned char TargetFlags) { 1134 assert((TargetFlags == 0 || isTarget) && 1135 "Cannot set target flags on target-independent jump tables"); 1136 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable; 1137 FoldingSetNodeID ID; 1138 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0); 1139 ID.AddInteger(JTI); 1140 ID.AddInteger(TargetFlags); 1141 void *IP = 0; 1142 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) 1143 return SDValue(E, 0); 1144 1145 SDNode *N = new (NodeAllocator) JumpTableSDNode(JTI, VT, isTarget, 1146 TargetFlags); 1147 CSEMap.InsertNode(N, IP); 1148 AllNodes.push_back(N); 1149 return SDValue(N, 0); 1150 } 1151 1152 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT, 1153 unsigned Alignment, int Offset, 1154 bool isTarget, 1155 unsigned char TargetFlags) { 1156 assert((TargetFlags == 0 || isTarget) && 1157 "Cannot set target flags on target-independent globals"); 1158 if (Alignment == 0) 1159 Alignment = 1160 TM.getTargetLowering()->getDataLayout()->getPrefTypeAlignment(C->getType()); 1161 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool; 1162 FoldingSetNodeID ID; 1163 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0); 1164 ID.AddInteger(Alignment); 1165 ID.AddInteger(Offset); 1166 ID.AddPointer(C); 1167 ID.AddInteger(TargetFlags); 1168 void *IP = 0; 1169 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) 1170 return SDValue(E, 0); 1171 1172 SDNode *N = new (NodeAllocator) ConstantPoolSDNode(isTarget, C, VT, Offset, 1173 Alignment, TargetFlags); 1174 CSEMap.InsertNode(N, IP); 1175 AllNodes.push_back(N); 1176 return SDValue(N, 0); 1177 } 1178 1179 1180 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT, 1181 unsigned Alignment, int Offset, 1182 bool isTarget, 1183 unsigned char TargetFlags) { 1184 assert((TargetFlags == 0 || isTarget) && 1185 "Cannot set target flags on target-independent globals"); 1186 if (Alignment == 0) 1187 Alignment = 1188 TM.getTargetLowering()->getDataLayout()->getPrefTypeAlignment(C->getType()); 1189 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool; 1190 FoldingSetNodeID ID; 1191 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0); 1192 ID.AddInteger(Alignment); 1193 ID.AddInteger(Offset); 1194 C->addSelectionDAGCSEId(ID); 1195 ID.AddInteger(TargetFlags); 1196 void *IP = 0; 1197 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) 1198 return SDValue(E, 0); 1199 1200 SDNode *N = new (NodeAllocator) ConstantPoolSDNode(isTarget, C, VT, Offset, 1201 Alignment, TargetFlags); 1202 CSEMap.InsertNode(N, IP); 1203 AllNodes.push_back(N); 1204 return SDValue(N, 0); 1205 } 1206 1207 SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset, 1208 unsigned char TargetFlags) { 1209 FoldingSetNodeID ID; 1210 AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), 0, 0); 1211 ID.AddInteger(Index); 1212 ID.AddInteger(Offset); 1213 ID.AddInteger(TargetFlags); 1214 void *IP = 0; 1215 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) 1216 return SDValue(E, 0); 1217 1218 SDNode *N = new (NodeAllocator) TargetIndexSDNode(Index, VT, Offset, 1219 TargetFlags); 1220 CSEMap.InsertNode(N, IP); 1221 AllNodes.push_back(N); 1222 return SDValue(N, 0); 1223 } 1224 1225 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) { 1226 FoldingSetNodeID ID; 1227 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), 0, 0); 1228 ID.AddPointer(MBB); 1229 void *IP = 0; 1230 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) 1231 return SDValue(E, 0); 1232 1233 SDNode *N = new (NodeAllocator) BasicBlockSDNode(MBB); 1234 CSEMap.InsertNode(N, IP); 1235 AllNodes.push_back(N); 1236 return SDValue(N, 0); 1237 } 1238 1239 SDValue SelectionDAG::getValueType(EVT VT) { 1240 if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >= 1241 ValueTypeNodes.size()) 1242 ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1); 1243 1244 SDNode *&N = VT.isExtended() ? 1245 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy]; 1246 1247 if (N) return SDValue(N, 0); 1248 N = new (NodeAllocator) VTSDNode(VT); 1249 AllNodes.push_back(N); 1250 return SDValue(N, 0); 1251 } 1252 1253 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) { 1254 SDNode *&N = ExternalSymbols[Sym]; 1255 if (N) return SDValue(N, 0); 1256 N = new (NodeAllocator) ExternalSymbolSDNode(false, Sym, 0, VT); 1257 AllNodes.push_back(N); 1258 return SDValue(N, 0); 1259 } 1260 1261 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT, 1262 unsigned char TargetFlags) { 1263 SDNode *&N = 1264 TargetExternalSymbols[std::pair<std::string,unsigned char>(Sym, 1265 TargetFlags)]; 1266 if (N) return SDValue(N, 0); 1267 N = new (NodeAllocator) ExternalSymbolSDNode(true, Sym, TargetFlags, VT); 1268 AllNodes.push_back(N); 1269 return SDValue(N, 0); 1270 } 1271 1272 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) { 1273 if ((unsigned)Cond >= CondCodeNodes.size()) 1274 CondCodeNodes.resize(Cond+1); 1275 1276 if (CondCodeNodes[Cond] == 0) { 1277 CondCodeSDNode *N = new (NodeAllocator) CondCodeSDNode(Cond); 1278 CondCodeNodes[Cond] = N; 1279 AllNodes.push_back(N); 1280 } 1281 1282 return SDValue(CondCodeNodes[Cond], 0); 1283 } 1284 1285 // commuteShuffle - swaps the values of N1 and N2, and swaps all indices in 1286 // the shuffle mask M that point at N1 to point at N2, and indices that point 1287 // N2 to point at N1. 1288 static void commuteShuffle(SDValue &N1, SDValue &N2, SmallVectorImpl<int> &M) { 1289 std::swap(N1, N2); 1290 int NElts = M.size(); 1291 for (int i = 0; i != NElts; ++i) { 1292 if (M[i] >= NElts) 1293 M[i] -= NElts; 1294 else if (M[i] >= 0) 1295 M[i] += NElts; 1296 } 1297 } 1298 1299 SDValue SelectionDAG::getVectorShuffle(EVT VT, SDLoc dl, SDValue N1, 1300 SDValue N2, const int *Mask) { 1301 assert(N1.getValueType() == N2.getValueType() && "Invalid VECTOR_SHUFFLE"); 1302 assert(VT.isVector() && N1.getValueType().isVector() && 1303 "Vector Shuffle VTs must be a vectors"); 1304 assert(VT.getVectorElementType() == N1.getValueType().getVectorElementType() 1305 && "Vector Shuffle VTs must have same element type"); 1306 1307 // Canonicalize shuffle undef, undef -> undef 1308 if (N1.getOpcode() == ISD::UNDEF && N2.getOpcode() == ISD::UNDEF) 1309 return getUNDEF(VT); 1310 1311 // Validate that all indices in Mask are within the range of the elements 1312 // input to the shuffle. 1313 unsigned NElts = VT.getVectorNumElements(); 1314 SmallVector<int, 8> MaskVec; 1315 for (unsigned i = 0; i != NElts; ++i) { 1316 assert(Mask[i] < (int)(NElts * 2) && "Index out of range"); 1317 MaskVec.push_back(Mask[i]); 1318 } 1319 1320 // Canonicalize shuffle v, v -> v, undef 1321 if (N1 == N2) { 1322 N2 = getUNDEF(VT); 1323 for (unsigned i = 0; i != NElts; ++i) 1324 if (MaskVec[i] >= (int)NElts) MaskVec[i] -= NElts; 1325 } 1326 1327 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask. 1328 if (N1.getOpcode() == ISD::UNDEF) 1329 commuteShuffle(N1, N2, MaskVec); 1330 1331 // Canonicalize all index into lhs, -> shuffle lhs, undef 1332 // Canonicalize all index into rhs, -> shuffle rhs, undef 1333 bool AllLHS = true, AllRHS = true; 1334 bool N2Undef = N2.getOpcode() == ISD::UNDEF; 1335 for (unsigned i = 0; i != NElts; ++i) { 1336 if (MaskVec[i] >= (int)NElts) { 1337 if (N2Undef) 1338 MaskVec[i] = -1; 1339 else 1340 AllLHS = false; 1341 } else if (MaskVec[i] >= 0) { 1342 AllRHS = false; 1343 } 1344 } 1345 if (AllLHS && AllRHS) 1346 return getUNDEF(VT); 1347 if (AllLHS && !N2Undef) 1348 N2 = getUNDEF(VT); 1349 if (AllRHS) { 1350 N1 = getUNDEF(VT); 1351 commuteShuffle(N1, N2, MaskVec); 1352 } 1353 1354 // If Identity shuffle, or all shuffle in to undef, return that node. 1355 bool AllUndef = true; 1356 bool Identity = true; 1357 for (unsigned i = 0; i != NElts; ++i) { 1358 if (MaskVec[i] >= 0 && MaskVec[i] != (int)i) Identity = false; 1359 if (MaskVec[i] >= 0) AllUndef = false; 1360 } 1361 if (Identity && NElts == N1.getValueType().getVectorNumElements()) 1362 return N1; 1363 if (AllUndef) 1364 return getUNDEF(VT); 1365 1366 FoldingSetNodeID ID; 1367 SDValue Ops[2] = { N1, N2 }; 1368 AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops, 2); 1369 for (unsigned i = 0; i != NElts; ++i) 1370 ID.AddInteger(MaskVec[i]); 1371 1372 void* IP = 0; 1373 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) 1374 return SDValue(E, 0); 1375 1376 // Allocate the mask array for the node out of the BumpPtrAllocator, since 1377 // SDNode doesn't have access to it. This memory will be "leaked" when 1378 // the node is deallocated, but recovered when the NodeAllocator is released. 1379 int *MaskAlloc = OperandAllocator.Allocate<int>(NElts); 1380 memcpy(MaskAlloc, &MaskVec[0], NElts * sizeof(int)); 1381 1382 ShuffleVectorSDNode *N = 1383 new (NodeAllocator) ShuffleVectorSDNode(VT, dl.getIROrder(), dl.getDebugLoc(), N1, N2, MaskAlloc); 1384 CSEMap.InsertNode(N, IP); 1385 AllNodes.push_back(N); 1386 return SDValue(N, 0); 1387 } 1388 1389 SDValue SelectionDAG::getConvertRndSat(EVT VT, SDLoc dl, 1390 SDValue Val, SDValue DTy, 1391 SDValue STy, SDValue Rnd, SDValue Sat, 1392 ISD::CvtCode Code) { 1393 // If the src and dest types are the same and the conversion is between 1394 // integer types of the same sign or two floats, no conversion is necessary. 1395 if (DTy == STy && 1396 (Code == ISD::CVT_UU || Code == ISD::CVT_SS || Code == ISD::CVT_FF)) 1397 return Val; 1398 1399 FoldingSetNodeID ID; 1400 SDValue Ops[] = { Val, DTy, STy, Rnd, Sat }; 1401 AddNodeIDNode(ID, ISD::CONVERT_RNDSAT, getVTList(VT), &Ops[0], 5); 1402 void* IP = 0; 1403 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) 1404 return SDValue(E, 0); 1405 1406 CvtRndSatSDNode *N = new (NodeAllocator) CvtRndSatSDNode(VT, dl.getIROrder(), dl.getDebugLoc(), Ops, 5, 1407 Code); 1408 CSEMap.InsertNode(N, IP); 1409 AllNodes.push_back(N); 1410 return SDValue(N, 0); 1411 } 1412 1413 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) { 1414 FoldingSetNodeID ID; 1415 AddNodeIDNode(ID, ISD::Register, getVTList(VT), 0, 0); 1416 ID.AddInteger(RegNo); 1417 void *IP = 0; 1418 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) 1419 return SDValue(E, 0); 1420 1421 SDNode *N = new (NodeAllocator) RegisterSDNode(RegNo, VT); 1422 CSEMap.InsertNode(N, IP); 1423 AllNodes.push_back(N); 1424 return SDValue(N, 0); 1425 } 1426 1427 SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) { 1428 FoldingSetNodeID ID; 1429 AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), 0, 0); 1430 ID.AddPointer(RegMask); 1431 void *IP = 0; 1432 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) 1433 return SDValue(E, 0); 1434 1435 SDNode *N = new (NodeAllocator) RegisterMaskSDNode(RegMask); 1436 CSEMap.InsertNode(N, IP); 1437 AllNodes.push_back(N); 1438 return SDValue(N, 0); 1439 } 1440 1441 SDValue SelectionDAG::getEHLabel(SDLoc dl, SDValue Root, MCSymbol *Label) { 1442 FoldingSetNodeID ID; 1443 SDValue Ops[] = { Root }; 1444 AddNodeIDNode(ID, ISD::EH_LABEL, getVTList(MVT::Other), &Ops[0], 1); 1445 ID.AddPointer(Label); 1446 void *IP = 0; 1447 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) 1448 return SDValue(E, 0); 1449 1450 SDNode *N = new (NodeAllocator) EHLabelSDNode(dl.getIROrder(), dl.getDebugLoc(), Root, Label); 1451 CSEMap.InsertNode(N, IP); 1452 AllNodes.push_back(N); 1453 return SDValue(N, 0); 1454 } 1455 1456 1457 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT, 1458 int64_t Offset, 1459 bool isTarget, 1460 unsigned char TargetFlags) { 1461 unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress; 1462 1463 FoldingSetNodeID ID; 1464 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0); 1465 ID.AddPointer(BA); 1466 ID.AddInteger(Offset); 1467 ID.AddInteger(TargetFlags); 1468 void *IP = 0; 1469 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) 1470 return SDValue(E, 0); 1471 1472 SDNode *N = new (NodeAllocator) BlockAddressSDNode(Opc, VT, BA, Offset, 1473 TargetFlags); 1474 CSEMap.InsertNode(N, IP); 1475 AllNodes.push_back(N); 1476 return SDValue(N, 0); 1477 } 1478 1479 SDValue SelectionDAG::getSrcValue(const Value *V) { 1480 assert((!V || V->getType()->isPointerTy()) && 1481 "SrcValue is not a pointer?"); 1482 1483 FoldingSetNodeID ID; 1484 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), 0, 0); 1485 ID.AddPointer(V); 1486 1487 void *IP = 0; 1488 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) 1489 return SDValue(E, 0); 1490 1491 SDNode *N = new (NodeAllocator) SrcValueSDNode(V); 1492 CSEMap.InsertNode(N, IP); 1493 AllNodes.push_back(N); 1494 return SDValue(N, 0); 1495 } 1496 1497 /// getMDNode - Return an MDNodeSDNode which holds an MDNode. 1498 SDValue SelectionDAG::getMDNode(const MDNode *MD) { 1499 FoldingSetNodeID ID; 1500 AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), 0, 0); 1501 ID.AddPointer(MD); 1502 1503 void *IP = 0; 1504 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) 1505 return SDValue(E, 0); 1506 1507 SDNode *N = new (NodeAllocator) MDNodeSDNode(MD); 1508 CSEMap.InsertNode(N, IP); 1509 AllNodes.push_back(N); 1510 return SDValue(N, 0); 1511 } 1512 1513 1514 /// getShiftAmountOperand - Return the specified value casted to 1515 /// the target's desired shift amount type. 1516 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) { 1517 EVT OpTy = Op.getValueType(); 1518 EVT ShTy = TM.getTargetLowering()->getShiftAmountTy(LHSTy); 1519 if (OpTy == ShTy || OpTy.isVector()) return Op; 1520 1521 ISD::NodeType Opcode = OpTy.bitsGT(ShTy) ? ISD::TRUNCATE : ISD::ZERO_EXTEND; 1522 return getNode(Opcode, SDLoc(Op), ShTy, Op); 1523 } 1524 1525 /// CreateStackTemporary - Create a stack temporary, suitable for holding the 1526 /// specified value type. 1527 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) { 1528 MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo(); 1529 unsigned ByteSize = VT.getStoreSize(); 1530 Type *Ty = VT.getTypeForEVT(*getContext()); 1531 const TargetLowering *TLI = TM.getTargetLowering(); 1532 unsigned StackAlign = 1533 std::max((unsigned)TLI->getDataLayout()->getPrefTypeAlignment(Ty), minAlign); 1534 1535 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false); 1536 return getFrameIndex(FrameIdx, TLI->getPointerTy()); 1537 } 1538 1539 /// CreateStackTemporary - Create a stack temporary suitable for holding 1540 /// either of the specified value types. 1541 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) { 1542 unsigned Bytes = std::max(VT1.getStoreSizeInBits(), 1543 VT2.getStoreSizeInBits())/8; 1544 Type *Ty1 = VT1.getTypeForEVT(*getContext()); 1545 Type *Ty2 = VT2.getTypeForEVT(*getContext()); 1546 const TargetLowering *TLI = TM.getTargetLowering(); 1547 const DataLayout *TD = TLI->getDataLayout(); 1548 unsigned Align = std::max(TD->getPrefTypeAlignment(Ty1), 1549 TD->getPrefTypeAlignment(Ty2)); 1550 1551 MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo(); 1552 int FrameIdx = FrameInfo->CreateStackObject(Bytes, Align, false); 1553 return getFrameIndex(FrameIdx, TLI->getPointerTy()); 1554 } 1555 1556 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, 1557 SDValue N2, ISD::CondCode Cond, SDLoc dl) { 1558 // These setcc operations always fold. 1559 switch (Cond) { 1560 default: break; 1561 case ISD::SETFALSE: 1562 case ISD::SETFALSE2: return getConstant(0, VT); 1563 case ISD::SETTRUE: 1564 case ISD::SETTRUE2: return getConstant(1, VT); 1565 1566 case ISD::SETOEQ: 1567 case ISD::SETOGT: 1568 case ISD::SETOGE: 1569 case ISD::SETOLT: 1570 case ISD::SETOLE: 1571 case ISD::SETONE: 1572 case ISD::SETO: 1573 case ISD::SETUO: 1574 case ISD::SETUEQ: 1575 case ISD::SETUNE: 1576 assert(!N1.getValueType().isInteger() && "Illegal setcc for integer!"); 1577 break; 1578 } 1579 1580 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode())) { 1581 const APInt &C2 = N2C->getAPIntValue(); 1582 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) { 1583 const APInt &C1 = N1C->getAPIntValue(); 1584 1585 switch (Cond) { 1586 default: llvm_unreachable("Unknown integer setcc!"); 1587 case ISD::SETEQ: return getConstant(C1 == C2, VT); 1588 case ISD::SETNE: return getConstant(C1 != C2, VT); 1589 case ISD::SETULT: return getConstant(C1.ult(C2), VT); 1590 case ISD::SETUGT: return getConstant(C1.ugt(C2), VT); 1591 case ISD::SETULE: return getConstant(C1.ule(C2), VT); 1592 case ISD::SETUGE: return getConstant(C1.uge(C2), VT); 1593 case ISD::SETLT: return getConstant(C1.slt(C2), VT); 1594 case ISD::SETGT: return getConstant(C1.sgt(C2), VT); 1595 case ISD::SETLE: return getConstant(C1.sle(C2), VT); 1596 case ISD::SETGE: return getConstant(C1.sge(C2), VT); 1597 } 1598 } 1599 } 1600 if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1.getNode())) { 1601 if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2.getNode())) { 1602 APFloat::cmpResult R = N1C->getValueAPF().compare(N2C->getValueAPF()); 1603 switch (Cond) { 1604 default: break; 1605 case ISD::SETEQ: if (R==APFloat::cmpUnordered) 1606 return getUNDEF(VT); 1607 // fall through 1608 case ISD::SETOEQ: return getConstant(R==APFloat::cmpEqual, VT); 1609 case ISD::SETNE: if (R==APFloat::cmpUnordered) 1610 return getUNDEF(VT); 1611 // fall through 1612 case ISD::SETONE: return getConstant(R==APFloat::cmpGreaterThan || 1613 R==APFloat::cmpLessThan, VT); 1614 case ISD::SETLT: if (R==APFloat::cmpUnordered) 1615 return getUNDEF(VT); 1616 // fall through 1617 case ISD::SETOLT: return getConstant(R==APFloat::cmpLessThan, VT); 1618 case ISD::SETGT: if (R==APFloat::cmpUnordered) 1619 return getUNDEF(VT); 1620 // fall through 1621 case ISD::SETOGT: return getConstant(R==APFloat::cmpGreaterThan, VT); 1622 case ISD::SETLE: if (R==APFloat::cmpUnordered) 1623 return getUNDEF(VT); 1624 // fall through 1625 case ISD::SETOLE: return getConstant(R==APFloat::cmpLessThan || 1626 R==APFloat::cmpEqual, VT); 1627 case ISD::SETGE: if (R==APFloat::cmpUnordered) 1628 return getUNDEF(VT); 1629 // fall through 1630 case ISD::SETOGE: return getConstant(R==APFloat::cmpGreaterThan || 1631 R==APFloat::cmpEqual, VT); 1632 case ISD::SETO: return getConstant(R!=APFloat::cmpUnordered, VT); 1633 case ISD::SETUO: return getConstant(R==APFloat::cmpUnordered, VT); 1634 case ISD::SETUEQ: return getConstant(R==APFloat::cmpUnordered || 1635 R==APFloat::cmpEqual, VT); 1636 case ISD::SETUNE: return getConstant(R!=APFloat::cmpEqual, VT); 1637 case ISD::SETULT: return getConstant(R==APFloat::cmpUnordered || 1638 R==APFloat::cmpLessThan, VT); 1639 case ISD::SETUGT: return getConstant(R==APFloat::cmpGreaterThan || 1640 R==APFloat::cmpUnordered, VT); 1641 case ISD::SETULE: return getConstant(R!=APFloat::cmpGreaterThan, VT); 1642 case ISD::SETUGE: return getConstant(R!=APFloat::cmpLessThan, VT); 1643 } 1644 } else { 1645 // Ensure that the constant occurs on the RHS. 1646 return getSetCC(dl, VT, N2, N1, ISD::getSetCCSwappedOperands(Cond)); 1647 } 1648 } 1649 1650 // Could not fold it. 1651 return SDValue(); 1652 } 1653 1654 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We 1655 /// use this predicate to simplify operations downstream. 1656 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const { 1657 // This predicate is not safe for vector operations. 1658 if (Op.getValueType().isVector()) 1659 return false; 1660 1661 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits(); 1662 return MaskedValueIsZero(Op, APInt::getSignBit(BitWidth), Depth); 1663 } 1664 1665 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use 1666 /// this predicate to simplify operations downstream. Mask is known to be zero 1667 /// for bits that V cannot have. 1668 bool SelectionDAG::MaskedValueIsZero(SDValue Op, const APInt &Mask, 1669 unsigned Depth) const { 1670 APInt KnownZero, KnownOne; 1671 ComputeMaskedBits(Op, KnownZero, KnownOne, Depth); 1672 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 1673 return (KnownZero & Mask) == Mask; 1674 } 1675 1676 /// ComputeMaskedBits - Determine which of the bits specified in Mask are 1677 /// known to be either zero or one and return them in the KnownZero/KnownOne 1678 /// bitsets. This code only analyzes bits in Mask, in order to short-circuit 1679 /// processing. 1680 void SelectionDAG::ComputeMaskedBits(SDValue Op, APInt &KnownZero, 1681 APInt &KnownOne, unsigned Depth) const { 1682 const TargetLowering *TLI = TM.getTargetLowering(); 1683 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits(); 1684 1685 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything. 1686 if (Depth == 6) 1687 return; // Limit search depth. 1688 1689 APInt KnownZero2, KnownOne2; 1690 1691 switch (Op.getOpcode()) { 1692 case ISD::Constant: 1693 // We know all of the bits for a constant! 1694 KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue(); 1695 KnownZero = ~KnownOne; 1696 return; 1697 case ISD::AND: 1698 // If either the LHS or the RHS are Zero, the result is zero. 1699 ComputeMaskedBits(Op.getOperand(1), KnownZero, KnownOne, Depth+1); 1700 ComputeMaskedBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1); 1701 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 1702 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 1703 1704 // Output known-1 bits are only known if set in both the LHS & RHS. 1705 KnownOne &= KnownOne2; 1706 // Output known-0 are known to be clear if zero in either the LHS | RHS. 1707 KnownZero |= KnownZero2; 1708 return; 1709 case ISD::OR: 1710 ComputeMaskedBits(Op.getOperand(1), KnownZero, KnownOne, Depth+1); 1711 ComputeMaskedBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1); 1712 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 1713 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 1714 1715 // Output known-0 bits are only known if clear in both the LHS & RHS. 1716 KnownZero &= KnownZero2; 1717 // Output known-1 are known to be set if set in either the LHS | RHS. 1718 KnownOne |= KnownOne2; 1719 return; 1720 case ISD::XOR: { 1721 ComputeMaskedBits(Op.getOperand(1), KnownZero, KnownOne, Depth+1); 1722 ComputeMaskedBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1); 1723 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 1724 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 1725 1726 // Output known-0 bits are known if clear or set in both the LHS & RHS. 1727 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2); 1728 // Output known-1 are known to be set if set in only one of the LHS, RHS. 1729 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2); 1730 KnownZero = KnownZeroOut; 1731 return; 1732 } 1733 case ISD::MUL: { 1734 ComputeMaskedBits(Op.getOperand(1), KnownZero, KnownOne, Depth+1); 1735 ComputeMaskedBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1); 1736 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 1737 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 1738 1739 // If low bits are zero in either operand, output low known-0 bits. 1740 // Also compute a conserative estimate for high known-0 bits. 1741 // More trickiness is possible, but this is sufficient for the 1742 // interesting case of alignment computation. 1743 KnownOne.clearAllBits(); 1744 unsigned TrailZ = KnownZero.countTrailingOnes() + 1745 KnownZero2.countTrailingOnes(); 1746 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() + 1747 KnownZero2.countLeadingOnes(), 1748 BitWidth) - BitWidth; 1749 1750 TrailZ = std::min(TrailZ, BitWidth); 1751 LeadZ = std::min(LeadZ, BitWidth); 1752 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) | 1753 APInt::getHighBitsSet(BitWidth, LeadZ); 1754 return; 1755 } 1756 case ISD::UDIV: { 1757 // For the purposes of computing leading zeros we can conservatively 1758 // treat a udiv as a logical right shift by the power of 2 known to 1759 // be less than the denominator. 1760 ComputeMaskedBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1); 1761 unsigned LeadZ = KnownZero2.countLeadingOnes(); 1762 1763 KnownOne2.clearAllBits(); 1764 KnownZero2.clearAllBits(); 1765 ComputeMaskedBits(Op.getOperand(1), KnownZero2, KnownOne2, Depth+1); 1766 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros(); 1767 if (RHSUnknownLeadingOnes != BitWidth) 1768 LeadZ = std::min(BitWidth, 1769 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1); 1770 1771 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ); 1772 return; 1773 } 1774 case ISD::SELECT: 1775 ComputeMaskedBits(Op.getOperand(2), KnownZero, KnownOne, Depth+1); 1776 ComputeMaskedBits(Op.getOperand(1), KnownZero2, KnownOne2, Depth+1); 1777 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 1778 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 1779 1780 // Only known if known in both the LHS and RHS. 1781 KnownOne &= KnownOne2; 1782 KnownZero &= KnownZero2; 1783 return; 1784 case ISD::SELECT_CC: 1785 ComputeMaskedBits(Op.getOperand(3), KnownZero, KnownOne, Depth+1); 1786 ComputeMaskedBits(Op.getOperand(2), KnownZero2, KnownOne2, Depth+1); 1787 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 1788 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 1789 1790 // Only known if known in both the LHS and RHS. 1791 KnownOne &= KnownOne2; 1792 KnownZero &= KnownZero2; 1793 return; 1794 case ISD::SADDO: 1795 case ISD::UADDO: 1796 case ISD::SSUBO: 1797 case ISD::USUBO: 1798 case ISD::SMULO: 1799 case ISD::UMULO: 1800 if (Op.getResNo() != 1) 1801 return; 1802 // The boolean result conforms to getBooleanContents. Fall through. 1803 case ISD::SETCC: 1804 // If we know the result of a setcc has the top bits zero, use this info. 1805 if (TLI->getBooleanContents(Op.getValueType().isVector()) == 1806 TargetLowering::ZeroOrOneBooleanContent && BitWidth > 1) 1807 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1); 1808 return; 1809 case ISD::SHL: 1810 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0 1811 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 1812 unsigned ShAmt = SA->getZExtValue(); 1813 1814 // If the shift count is an invalid immediate, don't do anything. 1815 if (ShAmt >= BitWidth) 1816 return; 1817 1818 ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1); 1819 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 1820 KnownZero <<= ShAmt; 1821 KnownOne <<= ShAmt; 1822 // low bits known zero. 1823 KnownZero |= APInt::getLowBitsSet(BitWidth, ShAmt); 1824 } 1825 return; 1826 case ISD::SRL: 1827 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0 1828 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 1829 unsigned ShAmt = SA->getZExtValue(); 1830 1831 // If the shift count is an invalid immediate, don't do anything. 1832 if (ShAmt >= BitWidth) 1833 return; 1834 1835 ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1); 1836 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 1837 KnownZero = KnownZero.lshr(ShAmt); 1838 KnownOne = KnownOne.lshr(ShAmt); 1839 1840 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt); 1841 KnownZero |= HighBits; // High bits known zero. 1842 } 1843 return; 1844 case ISD::SRA: 1845 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 1846 unsigned ShAmt = SA->getZExtValue(); 1847 1848 // If the shift count is an invalid immediate, don't do anything. 1849 if (ShAmt >= BitWidth) 1850 return; 1851 1852 // If any of the demanded bits are produced by the sign extension, we also 1853 // demand the input sign bit. 1854 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt); 1855 1856 ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1); 1857 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 1858 KnownZero = KnownZero.lshr(ShAmt); 1859 KnownOne = KnownOne.lshr(ShAmt); 1860 1861 // Handle the sign bits. 1862 APInt SignBit = APInt::getSignBit(BitWidth); 1863 SignBit = SignBit.lshr(ShAmt); // Adjust to where it is now in the mask. 1864 1865 if (KnownZero.intersects(SignBit)) { 1866 KnownZero |= HighBits; // New bits are known zero. 1867 } else if (KnownOne.intersects(SignBit)) { 1868 KnownOne |= HighBits; // New bits are known one. 1869 } 1870 } 1871 return; 1872 case ISD::SIGN_EXTEND_INREG: { 1873 EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 1874 unsigned EBits = EVT.getScalarType().getSizeInBits(); 1875 1876 // Sign extension. Compute the demanded bits in the result that are not 1877 // present in the input. 1878 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - EBits); 1879 1880 APInt InSignBit = APInt::getSignBit(EBits); 1881 APInt InputDemandedBits = APInt::getLowBitsSet(BitWidth, EBits); 1882 1883 // If the sign extended bits are demanded, we know that the sign 1884 // bit is demanded. 1885 InSignBit = InSignBit.zext(BitWidth); 1886 if (NewBits.getBoolValue()) 1887 InputDemandedBits |= InSignBit; 1888 1889 ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1); 1890 KnownOne &= InputDemandedBits; 1891 KnownZero &= InputDemandedBits; 1892 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 1893 1894 // If the sign bit of the input is known set or clear, then we know the 1895 // top bits of the result. 1896 if (KnownZero.intersects(InSignBit)) { // Input sign bit known clear 1897 KnownZero |= NewBits; 1898 KnownOne &= ~NewBits; 1899 } else if (KnownOne.intersects(InSignBit)) { // Input sign bit known set 1900 KnownOne |= NewBits; 1901 KnownZero &= ~NewBits; 1902 } else { // Input sign bit unknown 1903 KnownZero &= ~NewBits; 1904 KnownOne &= ~NewBits; 1905 } 1906 return; 1907 } 1908 case ISD::CTTZ: 1909 case ISD::CTTZ_ZERO_UNDEF: 1910 case ISD::CTLZ: 1911 case ISD::CTLZ_ZERO_UNDEF: 1912 case ISD::CTPOP: { 1913 unsigned LowBits = Log2_32(BitWidth)+1; 1914 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits); 1915 KnownOne.clearAllBits(); 1916 return; 1917 } 1918 case ISD::LOAD: { 1919 LoadSDNode *LD = cast<LoadSDNode>(Op); 1920 // If this is a ZEXTLoad and we are looking at the loaded value. 1921 if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) { 1922 EVT VT = LD->getMemoryVT(); 1923 unsigned MemBits = VT.getScalarType().getSizeInBits(); 1924 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits); 1925 } else if (const MDNode *Ranges = LD->getRanges()) { 1926 computeMaskedBitsLoad(*Ranges, KnownZero); 1927 } 1928 return; 1929 } 1930 case ISD::ZERO_EXTEND: { 1931 EVT InVT = Op.getOperand(0).getValueType(); 1932 unsigned InBits = InVT.getScalarType().getSizeInBits(); 1933 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits); 1934 KnownZero = KnownZero.trunc(InBits); 1935 KnownOne = KnownOne.trunc(InBits); 1936 ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1); 1937 KnownZero = KnownZero.zext(BitWidth); 1938 KnownOne = KnownOne.zext(BitWidth); 1939 KnownZero |= NewBits; 1940 return; 1941 } 1942 case ISD::SIGN_EXTEND: { 1943 EVT InVT = Op.getOperand(0).getValueType(); 1944 unsigned InBits = InVT.getScalarType().getSizeInBits(); 1945 APInt InSignBit = APInt::getSignBit(InBits); 1946 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits); 1947 1948 KnownZero = KnownZero.trunc(InBits); 1949 KnownOne = KnownOne.trunc(InBits); 1950 ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1); 1951 1952 // Note if the sign bit is known to be zero or one. 1953 bool SignBitKnownZero = KnownZero.isNegative(); 1954 bool SignBitKnownOne = KnownOne.isNegative(); 1955 assert(!(SignBitKnownZero && SignBitKnownOne) && 1956 "Sign bit can't be known to be both zero and one!"); 1957 1958 KnownZero = KnownZero.zext(BitWidth); 1959 KnownOne = KnownOne.zext(BitWidth); 1960 1961 // If the sign bit is known zero or one, the top bits match. 1962 if (SignBitKnownZero) 1963 KnownZero |= NewBits; 1964 else if (SignBitKnownOne) 1965 KnownOne |= NewBits; 1966 return; 1967 } 1968 case ISD::ANY_EXTEND: { 1969 EVT InVT = Op.getOperand(0).getValueType(); 1970 unsigned InBits = InVT.getScalarType().getSizeInBits(); 1971 KnownZero = KnownZero.trunc(InBits); 1972 KnownOne = KnownOne.trunc(InBits); 1973 ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1); 1974 KnownZero = KnownZero.zext(BitWidth); 1975 KnownOne = KnownOne.zext(BitWidth); 1976 return; 1977 } 1978 case ISD::TRUNCATE: { 1979 EVT InVT = Op.getOperand(0).getValueType(); 1980 unsigned InBits = InVT.getScalarType().getSizeInBits(); 1981 KnownZero = KnownZero.zext(InBits); 1982 KnownOne = KnownOne.zext(InBits); 1983 ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1); 1984 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 1985 KnownZero = KnownZero.trunc(BitWidth); 1986 KnownOne = KnownOne.trunc(BitWidth); 1987 break; 1988 } 1989 case ISD::AssertZext: { 1990 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 1991 APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits()); 1992 ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1); 1993 KnownZero |= (~InMask); 1994 KnownOne &= (~KnownZero); 1995 return; 1996 } 1997 case ISD::FGETSIGN: 1998 // All bits are zero except the low bit. 1999 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - 1); 2000 return; 2001 2002 case ISD::SUB: { 2003 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0))) { 2004 // We know that the top bits of C-X are clear if X contains less bits 2005 // than C (i.e. no wrap-around can happen). For example, 20-X is 2006 // positive if we can prove that X is >= 0 and < 16. 2007 if (CLHS->getAPIntValue().isNonNegative()) { 2008 unsigned NLZ = (CLHS->getAPIntValue()+1).countLeadingZeros(); 2009 // NLZ can't be BitWidth with no sign bit 2010 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1); 2011 ComputeMaskedBits(Op.getOperand(1), KnownZero2, KnownOne2, Depth+1); 2012 2013 // If all of the MaskV bits are known to be zero, then we know the 2014 // output top bits are zero, because we now know that the output is 2015 // from [0-C]. 2016 if ((KnownZero2 & MaskV) == MaskV) { 2017 unsigned NLZ2 = CLHS->getAPIntValue().countLeadingZeros(); 2018 // Top bits known zero. 2019 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2); 2020 } 2021 } 2022 } 2023 } 2024 // fall through 2025 case ISD::ADD: 2026 case ISD::ADDE: { 2027 // Output known-0 bits are known if clear or set in both the low clear bits 2028 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the 2029 // low 3 bits clear. 2030 ComputeMaskedBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1); 2031 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 2032 unsigned KnownZeroOut = KnownZero2.countTrailingOnes(); 2033 2034 ComputeMaskedBits(Op.getOperand(1), KnownZero2, KnownOne2, Depth+1); 2035 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 2036 KnownZeroOut = std::min(KnownZeroOut, 2037 KnownZero2.countTrailingOnes()); 2038 2039 if (Op.getOpcode() == ISD::ADD) { 2040 KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroOut); 2041 return; 2042 } 2043 2044 // With ADDE, a carry bit may be added in, so we can only use this 2045 // information if we know (at least) that the low two bits are clear. We 2046 // then return to the caller that the low bit is unknown but that other bits 2047 // are known zero. 2048 if (KnownZeroOut >= 2) // ADDE 2049 KnownZero |= APInt::getBitsSet(BitWidth, 1, KnownZeroOut); 2050 return; 2051 } 2052 case ISD::SREM: 2053 if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 2054 const APInt &RA = Rem->getAPIntValue().abs(); 2055 if (RA.isPowerOf2()) { 2056 APInt LowBits = RA - 1; 2057 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth); 2058 ComputeMaskedBits(Op.getOperand(0), KnownZero2,KnownOne2,Depth+1); 2059 2060 // The low bits of the first operand are unchanged by the srem. 2061 KnownZero = KnownZero2 & LowBits; 2062 KnownOne = KnownOne2 & LowBits; 2063 2064 // If the first operand is non-negative or has all low bits zero, then 2065 // the upper bits are all zero. 2066 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits)) 2067 KnownZero |= ~LowBits; 2068 2069 // If the first operand is negative and not all low bits are zero, then 2070 // the upper bits are all one. 2071 if (KnownOne2[BitWidth-1] && ((KnownOne2 & LowBits) != 0)) 2072 KnownOne |= ~LowBits; 2073 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 2074 } 2075 } 2076 return; 2077 case ISD::UREM: { 2078 if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 2079 const APInt &RA = Rem->getAPIntValue(); 2080 if (RA.isPowerOf2()) { 2081 APInt LowBits = (RA - 1); 2082 KnownZero |= ~LowBits; 2083 ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne,Depth+1); 2084 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 2085 break; 2086 } 2087 } 2088 2089 // Since the result is less than or equal to either operand, any leading 2090 // zero bits in either operand must also exist in the result. 2091 ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1); 2092 ComputeMaskedBits(Op.getOperand(1), KnownZero2, KnownOne2, Depth+1); 2093 2094 uint32_t Leaders = std::max(KnownZero.countLeadingOnes(), 2095 KnownZero2.countLeadingOnes()); 2096 KnownOne.clearAllBits(); 2097 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders); 2098 return; 2099 } 2100 case ISD::FrameIndex: 2101 case ISD::TargetFrameIndex: 2102 if (unsigned Align = InferPtrAlignment(Op)) { 2103 // The low bits are known zero if the pointer is aligned. 2104 KnownZero = APInt::getLowBitsSet(BitWidth, Log2_32(Align)); 2105 return; 2106 } 2107 break; 2108 2109 default: 2110 if (Op.getOpcode() < ISD::BUILTIN_OP_END) 2111 break; 2112 // Fallthrough 2113 case ISD::INTRINSIC_WO_CHAIN: 2114 case ISD::INTRINSIC_W_CHAIN: 2115 case ISD::INTRINSIC_VOID: 2116 // Allow the target to implement this method for its nodes. 2117 TLI->computeMaskedBitsForTargetNode(Op, KnownZero, KnownOne, *this, Depth); 2118 return; 2119 } 2120 } 2121 2122 /// ComputeNumSignBits - Return the number of times the sign bit of the 2123 /// register is replicated into the other bits. We know that at least 1 bit 2124 /// is always equal to the sign bit (itself), but other cases can give us 2125 /// information. For example, immediately after an "SRA X, 2", we know that 2126 /// the top 3 bits are all equal to each other, so we return 3. 2127 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const{ 2128 const TargetLowering *TLI = TM.getTargetLowering(); 2129 EVT VT = Op.getValueType(); 2130 assert(VT.isInteger() && "Invalid VT!"); 2131 unsigned VTBits = VT.getScalarType().getSizeInBits(); 2132 unsigned Tmp, Tmp2; 2133 unsigned FirstAnswer = 1; 2134 2135 if (Depth == 6) 2136 return 1; // Limit search depth. 2137 2138 switch (Op.getOpcode()) { 2139 default: break; 2140 case ISD::AssertSext: 2141 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits(); 2142 return VTBits-Tmp+1; 2143 case ISD::AssertZext: 2144 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits(); 2145 return VTBits-Tmp; 2146 2147 case ISD::Constant: { 2148 const APInt &Val = cast<ConstantSDNode>(Op)->getAPIntValue(); 2149 return Val.getNumSignBits(); 2150 } 2151 2152 case ISD::SIGN_EXTEND: 2153 Tmp = VTBits-Op.getOperand(0).getValueType().getScalarType().getSizeInBits(); 2154 return ComputeNumSignBits(Op.getOperand(0), Depth+1) + Tmp; 2155 2156 case ISD::SIGN_EXTEND_INREG: 2157 // Max of the input and what this extends. 2158 Tmp = 2159 cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarType().getSizeInBits(); 2160 Tmp = VTBits-Tmp+1; 2161 2162 Tmp2 = ComputeNumSignBits(Op.getOperand(0), Depth+1); 2163 return std::max(Tmp, Tmp2); 2164 2165 case ISD::SRA: 2166 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1); 2167 // SRA X, C -> adds C sign bits. 2168 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 2169 Tmp += C->getZExtValue(); 2170 if (Tmp > VTBits) Tmp = VTBits; 2171 } 2172 return Tmp; 2173 case ISD::SHL: 2174 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 2175 // shl destroys sign bits. 2176 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1); 2177 if (C->getZExtValue() >= VTBits || // Bad shift. 2178 C->getZExtValue() >= Tmp) break; // Shifted all sign bits out. 2179 return Tmp - C->getZExtValue(); 2180 } 2181 break; 2182 case ISD::AND: 2183 case ISD::OR: 2184 case ISD::XOR: // NOT is handled here. 2185 // Logical binary ops preserve the number of sign bits at the worst. 2186 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1); 2187 if (Tmp != 1) { 2188 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1); 2189 FirstAnswer = std::min(Tmp, Tmp2); 2190 // We computed what we know about the sign bits as our first 2191 // answer. Now proceed to the generic code that uses 2192 // ComputeMaskedBits, and pick whichever answer is better. 2193 } 2194 break; 2195 2196 case ISD::SELECT: 2197 Tmp = ComputeNumSignBits(Op.getOperand(1), Depth+1); 2198 if (Tmp == 1) return 1; // Early out. 2199 Tmp2 = ComputeNumSignBits(Op.getOperand(2), Depth+1); 2200 return std::min(Tmp, Tmp2); 2201 2202 case ISD::SADDO: 2203 case ISD::UADDO: 2204 case ISD::SSUBO: 2205 case ISD::USUBO: 2206 case ISD::SMULO: 2207 case ISD::UMULO: 2208 if (Op.getResNo() != 1) 2209 break; 2210 // The boolean result conforms to getBooleanContents. Fall through. 2211 case ISD::SETCC: 2212 // If setcc returns 0/-1, all bits are sign bits. 2213 if (TLI->getBooleanContents(Op.getValueType().isVector()) == 2214 TargetLowering::ZeroOrNegativeOneBooleanContent) 2215 return VTBits; 2216 break; 2217 case ISD::ROTL: 2218 case ISD::ROTR: 2219 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 2220 unsigned RotAmt = C->getZExtValue() & (VTBits-1); 2221 2222 // Handle rotate right by N like a rotate left by 32-N. 2223 if (Op.getOpcode() == ISD::ROTR) 2224 RotAmt = (VTBits-RotAmt) & (VTBits-1); 2225 2226 // If we aren't rotating out all of the known-in sign bits, return the 2227 // number that are left. This handles rotl(sext(x), 1) for example. 2228 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1); 2229 if (Tmp > RotAmt+1) return Tmp-RotAmt; 2230 } 2231 break; 2232 case ISD::ADD: 2233 // Add can have at most one carry bit. Thus we know that the output 2234 // is, at worst, one more bit than the inputs. 2235 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1); 2236 if (Tmp == 1) return 1; // Early out. 2237 2238 // Special case decrementing a value (ADD X, -1): 2239 if (ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 2240 if (CRHS->isAllOnesValue()) { 2241 APInt KnownZero, KnownOne; 2242 ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1); 2243 2244 // If the input is known to be 0 or 1, the output is 0/-1, which is all 2245 // sign bits set. 2246 if ((KnownZero | APInt(VTBits, 1)).isAllOnesValue()) 2247 return VTBits; 2248 2249 // If we are subtracting one from a positive number, there is no carry 2250 // out of the result. 2251 if (KnownZero.isNegative()) 2252 return Tmp; 2253 } 2254 2255 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1); 2256 if (Tmp2 == 1) return 1; 2257 return std::min(Tmp, Tmp2)-1; 2258 2259 case ISD::SUB: 2260 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1); 2261 if (Tmp2 == 1) return 1; 2262 2263 // Handle NEG. 2264 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0))) 2265 if (CLHS->isNullValue()) { 2266 APInt KnownZero, KnownOne; 2267 ComputeMaskedBits(Op.getOperand(1), KnownZero, KnownOne, Depth+1); 2268 // If the input is known to be 0 or 1, the output is 0/-1, which is all 2269 // sign bits set. 2270 if ((KnownZero | APInt(VTBits, 1)).isAllOnesValue()) 2271 return VTBits; 2272 2273 // If the input is known to be positive (the sign bit is known clear), 2274 // the output of the NEG has the same number of sign bits as the input. 2275 if (KnownZero.isNegative()) 2276 return Tmp2; 2277 2278 // Otherwise, we treat this like a SUB. 2279 } 2280 2281 // Sub can have at most one carry bit. Thus we know that the output 2282 // is, at worst, one more bit than the inputs. 2283 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1); 2284 if (Tmp == 1) return 1; // Early out. 2285 return std::min(Tmp, Tmp2)-1; 2286 case ISD::TRUNCATE: 2287 // FIXME: it's tricky to do anything useful for this, but it is an important 2288 // case for targets like X86. 2289 break; 2290 } 2291 2292 // If we are looking at the loaded value of the SDNode. 2293 if (Op.getResNo() == 0) { 2294 // Handle LOADX separately here. EXTLOAD case will fallthrough. 2295 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) { 2296 unsigned ExtType = LD->getExtensionType(); 2297 switch (ExtType) { 2298 default: break; 2299 case ISD::SEXTLOAD: // '17' bits known 2300 Tmp = LD->getMemoryVT().getScalarType().getSizeInBits(); 2301 return VTBits-Tmp+1; 2302 case ISD::ZEXTLOAD: // '16' bits known 2303 Tmp = LD->getMemoryVT().getScalarType().getSizeInBits(); 2304 return VTBits-Tmp; 2305 } 2306 } 2307 } 2308 2309 // Allow the target to implement this method for its nodes. 2310 if (Op.getOpcode() >= ISD::BUILTIN_OP_END || 2311 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 2312 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 2313 Op.getOpcode() == ISD::INTRINSIC_VOID) { 2314 unsigned NumBits = TLI->ComputeNumSignBitsForTargetNode(Op, Depth); 2315 if (NumBits > 1) FirstAnswer = std::max(FirstAnswer, NumBits); 2316 } 2317 2318 // Finally, if we can prove that the top bits of the result are 0's or 1's, 2319 // use this information. 2320 APInt KnownZero, KnownOne; 2321 ComputeMaskedBits(Op, KnownZero, KnownOne, Depth); 2322 2323 APInt Mask; 2324 if (KnownZero.isNegative()) { // sign bit is 0 2325 Mask = KnownZero; 2326 } else if (KnownOne.isNegative()) { // sign bit is 1; 2327 Mask = KnownOne; 2328 } else { 2329 // Nothing known. 2330 return FirstAnswer; 2331 } 2332 2333 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine 2334 // the number of identical bits in the top of the input value. 2335 Mask = ~Mask; 2336 Mask <<= Mask.getBitWidth()-VTBits; 2337 // Return # leading zeros. We use 'min' here in case Val was zero before 2338 // shifting. We don't want to return '64' as for an i32 "0". 2339 return std::max(FirstAnswer, std::min(VTBits, Mask.countLeadingZeros())); 2340 } 2341 2342 /// isBaseWithConstantOffset - Return true if the specified operand is an 2343 /// ISD::ADD with a ConstantSDNode on the right-hand side, or if it is an 2344 /// ISD::OR with a ConstantSDNode that is guaranteed to have the same 2345 /// semantics as an ADD. This handles the equivalence: 2346 /// X|Cst == X+Cst iff X&Cst = 0. 2347 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const { 2348 if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) || 2349 !isa<ConstantSDNode>(Op.getOperand(1))) 2350 return false; 2351 2352 if (Op.getOpcode() == ISD::OR && 2353 !MaskedValueIsZero(Op.getOperand(0), 2354 cast<ConstantSDNode>(Op.getOperand(1))->getAPIntValue())) 2355 return false; 2356 2357 return true; 2358 } 2359 2360 2361 bool SelectionDAG::isKnownNeverNaN(SDValue Op) const { 2362 // If we're told that NaNs won't happen, assume they won't. 2363 if (getTarget().Options.NoNaNsFPMath) 2364 return true; 2365 2366 // If the value is a constant, we can obviously see if it is a NaN or not. 2367 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 2368 return !C->getValueAPF().isNaN(); 2369 2370 // TODO: Recognize more cases here. 2371 2372 return false; 2373 } 2374 2375 bool SelectionDAG::isKnownNeverZero(SDValue Op) const { 2376 // If the value is a constant, we can obviously see if it is a zero or not. 2377 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 2378 return !C->isZero(); 2379 2380 // TODO: Recognize more cases here. 2381 switch (Op.getOpcode()) { 2382 default: break; 2383 case ISD::OR: 2384 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 2385 return !C->isNullValue(); 2386 break; 2387 } 2388 2389 return false; 2390 } 2391 2392 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const { 2393 // Check the obvious case. 2394 if (A == B) return true; 2395 2396 // For for negative and positive zero. 2397 if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) 2398 if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) 2399 if (CA->isZero() && CB->isZero()) return true; 2400 2401 // Otherwise they may not be equal. 2402 return false; 2403 } 2404 2405 /// getNode - Gets or creates the specified node. 2406 /// 2407 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, EVT VT) { 2408 FoldingSetNodeID ID; 2409 AddNodeIDNode(ID, Opcode, getVTList(VT), 0, 0); 2410 void *IP = 0; 2411 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) 2412 return SDValue(E, 0); 2413 2414 SDNode *N = new (NodeAllocator) SDNode(Opcode, DL.getIROrder(), DL.getDebugLoc(), getVTList(VT)); 2415 CSEMap.InsertNode(N, IP); 2416 2417 AllNodes.push_back(N); 2418 #ifndef NDEBUG 2419 VerifySDNode(N); 2420 #endif 2421 return SDValue(N, 0); 2422 } 2423 2424 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, 2425 EVT VT, SDValue Operand) { 2426 // Constant fold unary operations with an integer constant operand. 2427 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand.getNode())) { 2428 const APInt &Val = C->getAPIntValue(); 2429 switch (Opcode) { 2430 default: break; 2431 case ISD::SIGN_EXTEND: 2432 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), VT); 2433 case ISD::ANY_EXTEND: 2434 case ISD::ZERO_EXTEND: 2435 case ISD::TRUNCATE: 2436 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), VT); 2437 case ISD::UINT_TO_FP: 2438 case ISD::SINT_TO_FP: { 2439 APFloat apf(EVTToAPFloatSemantics(VT), 2440 APInt::getNullValue(VT.getSizeInBits())); 2441 (void)apf.convertFromAPInt(Val, 2442 Opcode==ISD::SINT_TO_FP, 2443 APFloat::rmNearestTiesToEven); 2444 return getConstantFP(apf, VT); 2445 } 2446 case ISD::BITCAST: 2447 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32) 2448 return getConstantFP(APFloat(APFloat::IEEEsingle, Val), VT); 2449 else if (VT == MVT::f64 && C->getValueType(0) == MVT::i64) 2450 return getConstantFP(APFloat(APFloat::IEEEdouble, Val), VT); 2451 break; 2452 case ISD::BSWAP: 2453 return getConstant(Val.byteSwap(), VT); 2454 case ISD::CTPOP: 2455 return getConstant(Val.countPopulation(), VT); 2456 case ISD::CTLZ: 2457 case ISD::CTLZ_ZERO_UNDEF: 2458 return getConstant(Val.countLeadingZeros(), VT); 2459 case ISD::CTTZ: 2460 case ISD::CTTZ_ZERO_UNDEF: 2461 return getConstant(Val.countTrailingZeros(), VT); 2462 } 2463 } 2464 2465 // Constant fold unary operations with a floating point constant operand. 2466 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand.getNode())) { 2467 APFloat V = C->getValueAPF(); // make copy 2468 switch (Opcode) { 2469 case ISD::FNEG: 2470 V.changeSign(); 2471 return getConstantFP(V, VT); 2472 case ISD::FABS: 2473 V.clearSign(); 2474 return getConstantFP(V, VT); 2475 case ISD::FCEIL: { 2476 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive); 2477 if (fs == APFloat::opOK || fs == APFloat::opInexact) 2478 return getConstantFP(V, VT); 2479 break; 2480 } 2481 case ISD::FTRUNC: { 2482 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero); 2483 if (fs == APFloat::opOK || fs == APFloat::opInexact) 2484 return getConstantFP(V, VT); 2485 break; 2486 } 2487 case ISD::FFLOOR: { 2488 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative); 2489 if (fs == APFloat::opOK || fs == APFloat::opInexact) 2490 return getConstantFP(V, VT); 2491 break; 2492 } 2493 case ISD::FP_EXTEND: { 2494 bool ignored; 2495 // This can return overflow, underflow, or inexact; we don't care. 2496 // FIXME need to be more flexible about rounding mode. 2497 (void)V.convert(EVTToAPFloatSemantics(VT), 2498 APFloat::rmNearestTiesToEven, &ignored); 2499 return getConstantFP(V, VT); 2500 } 2501 case ISD::FP_TO_SINT: 2502 case ISD::FP_TO_UINT: { 2503 integerPart x[2]; 2504 bool ignored; 2505 assert(integerPartWidth >= 64); 2506 // FIXME need to be more flexible about rounding mode. 2507 APFloat::opStatus s = V.convertToInteger(x, VT.getSizeInBits(), 2508 Opcode==ISD::FP_TO_SINT, 2509 APFloat::rmTowardZero, &ignored); 2510 if (s==APFloat::opInvalidOp) // inexact is OK, in fact usual 2511 break; 2512 APInt api(VT.getSizeInBits(), x); 2513 return getConstant(api, VT); 2514 } 2515 case ISD::BITCAST: 2516 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32) 2517 return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), VT); 2518 else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64) 2519 return getConstant(V.bitcastToAPInt().getZExtValue(), VT); 2520 break; 2521 } 2522 } 2523 2524 unsigned OpOpcode = Operand.getNode()->getOpcode(); 2525 switch (Opcode) { 2526 case ISD::TokenFactor: 2527 case ISD::MERGE_VALUES: 2528 case ISD::CONCAT_VECTORS: 2529 return Operand; // Factor, merge or concat of one node? No need. 2530 case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node"); 2531 case ISD::FP_EXTEND: 2532 assert(VT.isFloatingPoint() && 2533 Operand.getValueType().isFloatingPoint() && "Invalid FP cast!"); 2534 if (Operand.getValueType() == VT) return Operand; // noop conversion. 2535 assert((!VT.isVector() || 2536 VT.getVectorNumElements() == 2537 Operand.getValueType().getVectorNumElements()) && 2538 "Vector element count mismatch!"); 2539 if (Operand.getOpcode() == ISD::UNDEF) 2540 return getUNDEF(VT); 2541 break; 2542 case ISD::SIGN_EXTEND: 2543 assert(VT.isInteger() && Operand.getValueType().isInteger() && 2544 "Invalid SIGN_EXTEND!"); 2545 if (Operand.getValueType() == VT) return Operand; // noop extension 2546 assert(Operand.getValueType().getScalarType().bitsLT(VT.getScalarType()) && 2547 "Invalid sext node, dst < src!"); 2548 assert((!VT.isVector() || 2549 VT.getVectorNumElements() == 2550 Operand.getValueType().getVectorNumElements()) && 2551 "Vector element count mismatch!"); 2552 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND) 2553 return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0)); 2554 else if (OpOpcode == ISD::UNDEF) 2555 // sext(undef) = 0, because the top bits will all be the same. 2556 return getConstant(0, VT); 2557 break; 2558 case ISD::ZERO_EXTEND: 2559 assert(VT.isInteger() && Operand.getValueType().isInteger() && 2560 "Invalid ZERO_EXTEND!"); 2561 if (Operand.getValueType() == VT) return Operand; // noop extension 2562 assert(Operand.getValueType().getScalarType().bitsLT(VT.getScalarType()) && 2563 "Invalid zext node, dst < src!"); 2564 assert((!VT.isVector() || 2565 VT.getVectorNumElements() == 2566 Operand.getValueType().getVectorNumElements()) && 2567 "Vector element count mismatch!"); 2568 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x) 2569 return getNode(ISD::ZERO_EXTEND, DL, VT, 2570 Operand.getNode()->getOperand(0)); 2571 else if (OpOpcode == ISD::UNDEF) 2572 // zext(undef) = 0, because the top bits will be zero. 2573 return getConstant(0, VT); 2574 break; 2575 case ISD::ANY_EXTEND: 2576 assert(VT.isInteger() && Operand.getValueType().isInteger() && 2577 "Invalid ANY_EXTEND!"); 2578 if (Operand.getValueType() == VT) return Operand; // noop extension 2579 assert(Operand.getValueType().getScalarType().bitsLT(VT.getScalarType()) && 2580 "Invalid anyext node, dst < src!"); 2581 assert((!VT.isVector() || 2582 VT.getVectorNumElements() == 2583 Operand.getValueType().getVectorNumElements()) && 2584 "Vector element count mismatch!"); 2585 2586 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND || 2587 OpOpcode == ISD::ANY_EXTEND) 2588 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x) 2589 return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0)); 2590 else if (OpOpcode == ISD::UNDEF) 2591 return getUNDEF(VT); 2592 2593 // (ext (trunx x)) -> x 2594 if (OpOpcode == ISD::TRUNCATE) { 2595 SDValue OpOp = Operand.getNode()->getOperand(0); 2596 if (OpOp.getValueType() == VT) 2597 return OpOp; 2598 } 2599 break; 2600 case ISD::TRUNCATE: 2601 assert(VT.isInteger() && Operand.getValueType().isInteger() && 2602 "Invalid TRUNCATE!"); 2603 if (Operand.getValueType() == VT) return Operand; // noop truncate 2604 assert(Operand.getValueType().getScalarType().bitsGT(VT.getScalarType()) && 2605 "Invalid truncate node, src < dst!"); 2606 assert((!VT.isVector() || 2607 VT.getVectorNumElements() == 2608 Operand.getValueType().getVectorNumElements()) && 2609 "Vector element count mismatch!"); 2610 if (OpOpcode == ISD::TRUNCATE) 2611 return getNode(ISD::TRUNCATE, DL, VT, Operand.getNode()->getOperand(0)); 2612 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND || 2613 OpOpcode == ISD::ANY_EXTEND) { 2614 // If the source is smaller than the dest, we still need an extend. 2615 if (Operand.getNode()->getOperand(0).getValueType().getScalarType() 2616 .bitsLT(VT.getScalarType())) 2617 return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0)); 2618 if (Operand.getNode()->getOperand(0).getValueType().bitsGT(VT)) 2619 return getNode(ISD::TRUNCATE, DL, VT, Operand.getNode()->getOperand(0)); 2620 return Operand.getNode()->getOperand(0); 2621 } 2622 if (OpOpcode == ISD::UNDEF) 2623 return getUNDEF(VT); 2624 break; 2625 case ISD::BITCAST: 2626 // Basic sanity checking. 2627 assert(VT.getSizeInBits() == Operand.getValueType().getSizeInBits() 2628 && "Cannot BITCAST between types of different sizes!"); 2629 if (VT == Operand.getValueType()) return Operand; // noop conversion. 2630 if (OpOpcode == ISD::BITCAST) // bitconv(bitconv(x)) -> bitconv(x) 2631 return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0)); 2632 if (OpOpcode == ISD::UNDEF) 2633 return getUNDEF(VT); 2634 break; 2635 case ISD::SCALAR_TO_VECTOR: 2636 assert(VT.isVector() && !Operand.getValueType().isVector() && 2637 (VT.getVectorElementType() == Operand.getValueType() || 2638 (VT.getVectorElementType().isInteger() && 2639 Operand.getValueType().isInteger() && 2640 VT.getVectorElementType().bitsLE(Operand.getValueType()))) && 2641 "Illegal SCALAR_TO_VECTOR node!"); 2642 if (OpOpcode == ISD::UNDEF) 2643 return getUNDEF(VT); 2644 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined. 2645 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT && 2646 isa<ConstantSDNode>(Operand.getOperand(1)) && 2647 Operand.getConstantOperandVal(1) == 0 && 2648 Operand.getOperand(0).getValueType() == VT) 2649 return Operand.getOperand(0); 2650 break; 2651 case ISD::FNEG: 2652 // -(X-Y) -> (Y-X) is unsafe because when X==Y, -0.0 != +0.0 2653 if (getTarget().Options.UnsafeFPMath && OpOpcode == ISD::FSUB) 2654 return getNode(ISD::FSUB, DL, VT, Operand.getNode()->getOperand(1), 2655 Operand.getNode()->getOperand(0)); 2656 if (OpOpcode == ISD::FNEG) // --X -> X 2657 return Operand.getNode()->getOperand(0); 2658 break; 2659 case ISD::FABS: 2660 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X) 2661 return getNode(ISD::FABS, DL, VT, Operand.getNode()->getOperand(0)); 2662 break; 2663 } 2664 2665 SDNode *N; 2666 SDVTList VTs = getVTList(VT); 2667 if (VT != MVT::Glue) { // Don't CSE flag producing nodes 2668 FoldingSetNodeID ID; 2669 SDValue Ops[1] = { Operand }; 2670 AddNodeIDNode(ID, Opcode, VTs, Ops, 1); 2671 void *IP = 0; 2672 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) 2673 return SDValue(E, 0); 2674 2675 N = new (NodeAllocator) UnarySDNode(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs, Operand); 2676 CSEMap.InsertNode(N, IP); 2677 } else { 2678 N = new (NodeAllocator) UnarySDNode(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs, Operand); 2679 } 2680 2681 AllNodes.push_back(N); 2682 #ifndef NDEBUG 2683 VerifySDNode(N); 2684 #endif 2685 return SDValue(N, 0); 2686 } 2687 2688 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, EVT VT, 2689 SDNode *Cst1, SDNode *Cst2) { 2690 SmallVector<std::pair<ConstantSDNode *, ConstantSDNode *>, 4> Inputs; 2691 SmallVector<SDValue, 4> Outputs; 2692 EVT SVT = VT.getScalarType(); 2693 2694 ConstantSDNode *Scalar1 = dyn_cast<ConstantSDNode>(Cst1); 2695 ConstantSDNode *Scalar2 = dyn_cast<ConstantSDNode>(Cst2); 2696 if (Scalar1 && Scalar2) { 2697 // Scalar instruction. 2698 Inputs.push_back(std::make_pair(Scalar1, Scalar2)); 2699 } else { 2700 // For vectors extract each constant element into Inputs so we can constant 2701 // fold them individually. 2702 BuildVectorSDNode *BV1 = dyn_cast<BuildVectorSDNode>(Cst1); 2703 BuildVectorSDNode *BV2 = dyn_cast<BuildVectorSDNode>(Cst2); 2704 if (!BV1 || !BV2) 2705 return SDValue(); 2706 2707 assert(BV1->getNumOperands() == BV2->getNumOperands() && "Out of sync!"); 2708 2709 for (unsigned I = 0, E = BV1->getNumOperands(); I != E; ++I) { 2710 ConstantSDNode *V1 = dyn_cast<ConstantSDNode>(BV1->getOperand(I)); 2711 ConstantSDNode *V2 = dyn_cast<ConstantSDNode>(BV2->getOperand(I)); 2712 if (!V1 || !V2) // Not a constant, bail. 2713 return SDValue(); 2714 2715 // Avoid BUILD_VECTOR nodes that perform implicit truncation. 2716 // FIXME: This is valid and could be handled by truncating the APInts. 2717 if (V1->getValueType(0) != SVT || V2->getValueType(0) != SVT) 2718 return SDValue(); 2719 2720 Inputs.push_back(std::make_pair(V1, V2)); 2721 } 2722 } 2723 2724 // We have a number of constant values, constant fold them element by element. 2725 for (unsigned I = 0, E = Inputs.size(); I != E; ++I) { 2726 const APInt &C1 = Inputs[I].first->getAPIntValue(); 2727 const APInt &C2 = Inputs[I].second->getAPIntValue(); 2728 2729 switch (Opcode) { 2730 case ISD::ADD: 2731 Outputs.push_back(getConstant(C1 + C2, SVT)); 2732 break; 2733 case ISD::SUB: 2734 Outputs.push_back(getConstant(C1 - C2, SVT)); 2735 break; 2736 case ISD::MUL: 2737 Outputs.push_back(getConstant(C1 * C2, SVT)); 2738 break; 2739 case ISD::UDIV: 2740 if (!C2.getBoolValue()) 2741 return SDValue(); 2742 Outputs.push_back(getConstant(C1.udiv(C2), SVT)); 2743 break; 2744 case ISD::UREM: 2745 if (!C2.getBoolValue()) 2746 return SDValue(); 2747 Outputs.push_back(getConstant(C1.urem(C2), SVT)); 2748 break; 2749 case ISD::SDIV: 2750 if (!C2.getBoolValue()) 2751 return SDValue(); 2752 Outputs.push_back(getConstant(C1.sdiv(C2), SVT)); 2753 break; 2754 case ISD::SREM: 2755 if (!C2.getBoolValue()) 2756 return SDValue(); 2757 Outputs.push_back(getConstant(C1.srem(C2), SVT)); 2758 break; 2759 case ISD::AND: 2760 Outputs.push_back(getConstant(C1 & C2, SVT)); 2761 break; 2762 case ISD::OR: 2763 Outputs.push_back(getConstant(C1 | C2, SVT)); 2764 break; 2765 case ISD::XOR: 2766 Outputs.push_back(getConstant(C1 ^ C2, SVT)); 2767 break; 2768 case ISD::SHL: 2769 Outputs.push_back(getConstant(C1 << C2, SVT)); 2770 break; 2771 case ISD::SRL: 2772 Outputs.push_back(getConstant(C1.lshr(C2), SVT)); 2773 break; 2774 case ISD::SRA: 2775 Outputs.push_back(getConstant(C1.ashr(C2), SVT)); 2776 break; 2777 case ISD::ROTL: 2778 Outputs.push_back(getConstant(C1.rotl(C2), SVT)); 2779 break; 2780 case ISD::ROTR: 2781 Outputs.push_back(getConstant(C1.rotr(C2), SVT)); 2782 break; 2783 default: 2784 return SDValue(); 2785 } 2786 } 2787 2788 // Handle the scalar case first. 2789 if (Scalar1 && Scalar2) 2790 return Outputs.back(); 2791 2792 // Otherwise build a big vector out of the scalar elements we generated. 2793 return getNode(ISD::BUILD_VECTOR, SDLoc(), VT, Outputs.data(), 2794 Outputs.size()); 2795 } 2796 2797 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, EVT VT, SDValue N1, 2798 SDValue N2) { 2799 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 2800 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode()); 2801 switch (Opcode) { 2802 default: break; 2803 case ISD::TokenFactor: 2804 assert(VT == MVT::Other && N1.getValueType() == MVT::Other && 2805 N2.getValueType() == MVT::Other && "Invalid token factor!"); 2806 // Fold trivial token factors. 2807 if (N1.getOpcode() == ISD::EntryToken) return N2; 2808 if (N2.getOpcode() == ISD::EntryToken) return N1; 2809 if (N1 == N2) return N1; 2810 break; 2811 case ISD::CONCAT_VECTORS: 2812 // Concat of UNDEFs is UNDEF. 2813 if (N1.getOpcode() == ISD::UNDEF && 2814 N2.getOpcode() == ISD::UNDEF) 2815 return getUNDEF(VT); 2816 2817 // A CONCAT_VECTOR with all operands BUILD_VECTOR can be simplified to 2818 // one big BUILD_VECTOR. 2819 if (N1.getOpcode() == ISD::BUILD_VECTOR && 2820 N2.getOpcode() == ISD::BUILD_VECTOR) { 2821 SmallVector<SDValue, 16> Elts(N1.getNode()->op_begin(), 2822 N1.getNode()->op_end()); 2823 Elts.append(N2.getNode()->op_begin(), N2.getNode()->op_end()); 2824 return getNode(ISD::BUILD_VECTOR, DL, VT, &Elts[0], Elts.size()); 2825 } 2826 break; 2827 case ISD::AND: 2828 assert(VT.isInteger() && "This operator does not apply to FP types!"); 2829 assert(N1.getValueType() == N2.getValueType() && 2830 N1.getValueType() == VT && "Binary operator types must match!"); 2831 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's 2832 // worth handling here. 2833 if (N2C && N2C->isNullValue()) 2834 return N2; 2835 if (N2C && N2C->isAllOnesValue()) // X & -1 -> X 2836 return N1; 2837 break; 2838 case ISD::OR: 2839 case ISD::XOR: 2840 case ISD::ADD: 2841 case ISD::SUB: 2842 assert(VT.isInteger() && "This operator does not apply to FP types!"); 2843 assert(N1.getValueType() == N2.getValueType() && 2844 N1.getValueType() == VT && "Binary operator types must match!"); 2845 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so 2846 // it's worth handling here. 2847 if (N2C && N2C->isNullValue()) 2848 return N1; 2849 break; 2850 case ISD::UDIV: 2851 case ISD::UREM: 2852 case ISD::MULHU: 2853 case ISD::MULHS: 2854 case ISD::MUL: 2855 case ISD::SDIV: 2856 case ISD::SREM: 2857 assert(VT.isInteger() && "This operator does not apply to FP types!"); 2858 assert(N1.getValueType() == N2.getValueType() && 2859 N1.getValueType() == VT && "Binary operator types must match!"); 2860 break; 2861 case ISD::FADD: 2862 case ISD::FSUB: 2863 case ISD::FMUL: 2864 case ISD::FDIV: 2865 case ISD::FREM: 2866 if (getTarget().Options.UnsafeFPMath) { 2867 if (Opcode == ISD::FADD) { 2868 // 0+x --> x 2869 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) 2870 if (CFP->getValueAPF().isZero()) 2871 return N2; 2872 // x+0 --> x 2873 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N2)) 2874 if (CFP->getValueAPF().isZero()) 2875 return N1; 2876 } else if (Opcode == ISD::FSUB) { 2877 // x-0 --> x 2878 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N2)) 2879 if (CFP->getValueAPF().isZero()) 2880 return N1; 2881 } else if (Opcode == ISD::FMUL) { 2882 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1); 2883 SDValue V = N2; 2884 2885 // If the first operand isn't the constant, try the second 2886 if (!CFP) { 2887 CFP = dyn_cast<ConstantFPSDNode>(N2); 2888 V = N1; 2889 } 2890 2891 if (CFP) { 2892 // 0*x --> 0 2893 if (CFP->isZero()) 2894 return SDValue(CFP,0); 2895 // 1*x --> x 2896 if (CFP->isExactlyValue(1.0)) 2897 return V; 2898 } 2899 } 2900 } 2901 assert(VT.isFloatingPoint() && "This operator only applies to FP types!"); 2902 assert(N1.getValueType() == N2.getValueType() && 2903 N1.getValueType() == VT && "Binary operator types must match!"); 2904 break; 2905 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match. 2906 assert(N1.getValueType() == VT && 2907 N1.getValueType().isFloatingPoint() && 2908 N2.getValueType().isFloatingPoint() && 2909 "Invalid FCOPYSIGN!"); 2910 break; 2911 case ISD::SHL: 2912 case ISD::SRA: 2913 case ISD::SRL: 2914 case ISD::ROTL: 2915 case ISD::ROTR: 2916 assert(VT == N1.getValueType() && 2917 "Shift operators return type must be the same as their first arg"); 2918 assert(VT.isInteger() && N2.getValueType().isInteger() && 2919 "Shifts only work on integers"); 2920 assert((!VT.isVector() || VT == N2.getValueType()) && 2921 "Vector shift amounts must be in the same as their first arg"); 2922 // Verify that the shift amount VT is bit enough to hold valid shift 2923 // amounts. This catches things like trying to shift an i1024 value by an 2924 // i8, which is easy to fall into in generic code that uses 2925 // TLI.getShiftAmount(). 2926 assert(N2.getValueType().getSizeInBits() >= 2927 Log2_32_Ceil(N1.getValueType().getSizeInBits()) && 2928 "Invalid use of small shift amount with oversized value!"); 2929 2930 // Always fold shifts of i1 values so the code generator doesn't need to 2931 // handle them. Since we know the size of the shift has to be less than the 2932 // size of the value, the shift/rotate count is guaranteed to be zero. 2933 if (