1 //===-- SelectionDAG.cpp - Implement the SelectionDAG data structures -----===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This implements the SelectionDAG class.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/CodeGen/SelectionDAG.h"
15 #include "llvm/Constants.h"
16 #include "llvm/GlobalVariable.h"
17 #include "llvm/Intrinsics.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Assembly/Writer.h"
20 #include "llvm/CodeGen/MachineBasicBlock.h"
21 #include "llvm/CodeGen/MachineConstantPool.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/PseudoSourceValue.h"
24 #include "llvm/Support/MathExtras.h"
25 #include "llvm/Target/MRegisterInfo.h"
26 #include "llvm/Target/TargetData.h"
27 #include "llvm/Target/TargetLowering.h"
28 #include "llvm/Target/TargetInstrInfo.h"
29 #include "llvm/Target/TargetMachine.h"
30 #include "llvm/ADT/SetVector.h"
31 #include "llvm/ADT/SmallPtrSet.h"
32 #include "llvm/ADT/SmallSet.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/StringExtras.h"
39 /// makeVTList - Return an instance of the SDVTList struct initialized with the
40 /// specified members.
41 static SDVTList makeVTList(const MVT::ValueType *VTs, unsigned NumVTs) {
42 SDVTList Res = {VTs, NumVTs};
46 //===----------------------------------------------------------------------===//
47 // ConstantFPSDNode Class
48 //===----------------------------------------------------------------------===//
50 /// isExactlyValue - We don't rely on operator== working on double values, as
51 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
52 /// As such, this method can be used to do an exact bit-for-bit comparison of
53 /// two floating point values.
54 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
55 return Value.bitwiseIsEqual(V);
58 bool ConstantFPSDNode::isValueValidForType(MVT::ValueType VT,
60 // convert modifies in place, so make a copy.
61 APFloat Val2 = APFloat(Val);
64 return false; // These can't be represented as floating point!
66 // FIXME rounding mode needs to be more flexible
68 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
69 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven) ==
72 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
73 &Val2.getSemantics() == &APFloat::IEEEdouble ||
74 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven) ==
76 // TODO: Figure out how to test if we can use a shorter type instead!
84 //===----------------------------------------------------------------------===//
86 //===----------------------------------------------------------------------===//
88 /// isBuildVectorAllOnes - Return true if the specified node is a
89 /// BUILD_VECTOR where all of the elements are ~0 or undef.
90 bool ISD::isBuildVectorAllOnes(const SDNode *N) {
91 // Look through a bit convert.
92 if (N->getOpcode() == ISD::BIT_CONVERT)
93 N = N->getOperand(0).Val;
95 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
97 unsigned i = 0, e = N->getNumOperands();
99 // Skip over all of the undef values.
100 while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
103 // Do not accept an all-undef vector.
104 if (i == e) return false;
106 // Do not accept build_vectors that aren't all constants or which have non-~0
108 SDOperand NotZero = N->getOperand(i);
109 if (isa<ConstantSDNode>(NotZero)) {
110 if (!cast<ConstantSDNode>(NotZero)->isAllOnesValue())
112 } else if (isa<ConstantFPSDNode>(NotZero)) {
113 MVT::ValueType VT = NotZero.getValueType();
115 if (((cast<ConstantFPSDNode>(NotZero)->getValueAPF().
116 convertToAPInt().getZExtValue())) != (uint64_t)-1)
119 if ((uint32_t)cast<ConstantFPSDNode>(NotZero)->
120 getValueAPF().convertToAPInt().getZExtValue() !=
127 // Okay, we have at least one ~0 value, check to see if the rest match or are
129 for (++i; i != e; ++i)
130 if (N->getOperand(i) != NotZero &&
131 N->getOperand(i).getOpcode() != ISD::UNDEF)
137 /// isBuildVectorAllZeros - Return true if the specified node is a
138 /// BUILD_VECTOR where all of the elements are 0 or undef.
139 bool ISD::isBuildVectorAllZeros(const SDNode *N) {
140 // Look through a bit convert.
141 if (N->getOpcode() == ISD::BIT_CONVERT)
142 N = N->getOperand(0).Val;
144 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
146 unsigned i = 0, e = N->getNumOperands();
148 // Skip over all of the undef values.
149 while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
152 // Do not accept an all-undef vector.
153 if (i == e) return false;
155 // Do not accept build_vectors that aren't all constants or which have non-~0
157 SDOperand Zero = N->getOperand(i);
158 if (isa<ConstantSDNode>(Zero)) {
159 if (!cast<ConstantSDNode>(Zero)->isNullValue())
161 } else if (isa<ConstantFPSDNode>(Zero)) {
162 if (!cast<ConstantFPSDNode>(Zero)->getValueAPF().isPosZero())
167 // Okay, we have at least one ~0 value, check to see if the rest match or are
169 for (++i; i != e; ++i)
170 if (N->getOperand(i) != Zero &&
171 N->getOperand(i).getOpcode() != ISD::UNDEF)
176 /// getSetCCSwappedOperands - Return the operation corresponding to (Y op X)
177 /// when given the operation for (X op Y).
178 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
179 // To perform this operation, we just need to swap the L and G bits of the
181 unsigned OldL = (Operation >> 2) & 1;
182 unsigned OldG = (Operation >> 1) & 1;
183 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits
184 (OldL << 1) | // New G bit
185 (OldG << 2)); // New L bit.
188 /// getSetCCInverse - Return the operation corresponding to !(X op Y), where
189 /// 'op' is a valid SetCC operation.
190 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, bool isInteger) {
191 unsigned Operation = Op;
193 Operation ^= 7; // Flip L, G, E bits, but not U.
195 Operation ^= 15; // Flip all of the condition bits.
196 if (Operation > ISD::SETTRUE2)
197 Operation &= ~8; // Don't let N and U bits get set.
198 return ISD::CondCode(Operation);
202 /// isSignedOp - For an integer comparison, return 1 if the comparison is a
203 /// signed operation and 2 if the result is an unsigned comparison. Return zero
204 /// if the operation does not depend on the sign of the input (setne and seteq).
205 static int isSignedOp(ISD::CondCode Opcode) {
207 default: assert(0 && "Illegal integer setcc operation!");
209 case ISD::SETNE: return 0;
213 case ISD::SETGE: return 1;
217 case ISD::SETUGE: return 2;
221 /// getSetCCOrOperation - Return the result of a logical OR between different
222 /// comparisons of identical values: ((X op1 Y) | (X op2 Y)). This function
223 /// returns SETCC_INVALID if it is not possible to represent the resultant
225 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
227 if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
228 // Cannot fold a signed integer setcc with an unsigned integer setcc.
229 return ISD::SETCC_INVALID;
231 unsigned Op = Op1 | Op2; // Combine all of the condition bits.
233 // If the N and U bits get set then the resultant comparison DOES suddenly
234 // care about orderedness, and is true when ordered.
235 if (Op > ISD::SETTRUE2)
236 Op &= ~16; // Clear the U bit if the N bit is set.
238 // Canonicalize illegal integer setcc's.
239 if (isInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT
242 return ISD::CondCode(Op);
245 /// getSetCCAndOperation - Return the result of a logical AND between different
246 /// comparisons of identical values: ((X op1 Y) & (X op2 Y)). This
247 /// function returns zero if it is not possible to represent the resultant
249 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
251 if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
252 // Cannot fold a signed setcc with an unsigned setcc.
253 return ISD::SETCC_INVALID;
255 // Combine all of the condition bits.
256 ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
258 // Canonicalize illegal integer setcc's.
262 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT
263 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE
264 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE
265 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE
272 const TargetMachine &SelectionDAG::getTarget() const {
273 return TLI.getTargetMachine();
276 //===----------------------------------------------------------------------===//
277 // SDNode Profile Support
278 //===----------------------------------------------------------------------===//
280 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
282 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) {
286 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
287 /// solely with their pointer.
288 void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
289 ID.AddPointer(VTList.VTs);
292 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
294 static void AddNodeIDOperands(FoldingSetNodeID &ID,
295 const SDOperand *Ops, unsigned NumOps) {
296 for (; NumOps; --NumOps, ++Ops) {
297 ID.AddPointer(Ops->Val);
298 ID.AddInteger(Ops->ResNo);
302 static void AddNodeIDNode(FoldingSetNodeID &ID,
303 unsigned short OpC, SDVTList VTList,
304 const SDOperand *OpList, unsigned N) {
305 AddNodeIDOpcode(ID, OpC);
306 AddNodeIDValueTypes(ID, VTList);
307 AddNodeIDOperands(ID, OpList, N);
310 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
312 static void AddNodeIDNode(FoldingSetNodeID &ID, SDNode *N) {
313 AddNodeIDOpcode(ID, N->getOpcode());
314 // Add the return value info.
315 AddNodeIDValueTypes(ID, N->getVTList());
316 // Add the operand info.
317 AddNodeIDOperands(ID, N->op_begin(), N->getNumOperands());
319 // Handle SDNode leafs with special info.
320 switch (N->getOpcode()) {
321 default: break; // Normal nodes don't need extra info.
322 case ISD::TargetConstant:
324 ID.AddInteger(cast<ConstantSDNode>(N)->getValue());
326 case ISD::TargetConstantFP:
327 case ISD::ConstantFP: {
328 ID.AddAPFloat(cast<ConstantFPSDNode>(N)->getValueAPF());
331 case ISD::TargetGlobalAddress:
332 case ISD::GlobalAddress:
333 case ISD::TargetGlobalTLSAddress:
334 case ISD::GlobalTLSAddress: {
335 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
336 ID.AddPointer(GA->getGlobal());
337 ID.AddInteger(GA->getOffset());
340 case ISD::BasicBlock:
341 ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
344 ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
347 ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
349 case ISD::MEMOPERAND: {
350 const MemOperand &MO = cast<MemOperandSDNode>(N)->MO;
351 ID.AddPointer(MO.getValue());
352 ID.AddInteger(MO.getFlags());
353 ID.AddInteger(MO.getOffset());
354 ID.AddInteger(MO.getSize());
355 ID.AddInteger(MO.getAlignment());
358 case ISD::FrameIndex:
359 case ISD::TargetFrameIndex:
360 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
363 case ISD::TargetJumpTable:
364 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
366 case ISD::ConstantPool:
367 case ISD::TargetConstantPool: {
368 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
369 ID.AddInteger(CP->getAlignment());
370 ID.AddInteger(CP->getOffset());
371 if (CP->isMachineConstantPoolEntry())
372 CP->getMachineCPVal()->AddSelectionDAGCSEId(ID);
374 ID.AddPointer(CP->getConstVal());
378 LoadSDNode *LD = cast<LoadSDNode>(N);
379 ID.AddInteger(LD->getAddressingMode());
380 ID.AddInteger(LD->getExtensionType());
381 ID.AddInteger((unsigned int)(LD->getMemoryVT()));
382 ID.AddInteger(LD->getAlignment());
383 ID.AddInteger(LD->isVolatile());
387 StoreSDNode *ST = cast<StoreSDNode>(N);
388 ID.AddInteger(ST->getAddressingMode());
389 ID.AddInteger(ST->isTruncatingStore());
390 ID.AddInteger((unsigned int)(ST->getMemoryVT()));
391 ID.AddInteger(ST->getAlignment());
392 ID.AddInteger(ST->isVolatile());
398 //===----------------------------------------------------------------------===//
399 // SelectionDAG Class
400 //===----------------------------------------------------------------------===//
402 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
404 void SelectionDAG::RemoveDeadNodes() {
405 // Create a dummy node (which is not added to allnodes), that adds a reference
406 // to the root node, preventing it from being deleted.
407 HandleSDNode Dummy(getRoot());
409 SmallVector<SDNode*, 128> DeadNodes;
411 // Add all obviously-dead nodes to the DeadNodes worklist.
412 for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I)
414 DeadNodes.push_back(I);
416 // Process the worklist, deleting the nodes and adding their uses to the
418 while (!DeadNodes.empty()) {
419 SDNode *N = DeadNodes.back();
420 DeadNodes.pop_back();
422 // Take the node out of the appropriate CSE map.
423 RemoveNodeFromCSEMaps(N);
425 // Next, brutally remove the operand list. This is safe to do, as there are
426 // no cycles in the graph.
427 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
428 SDNode *Operand = I->Val;
429 Operand->removeUser(N);
431 // Now that we removed this operand, see if there are no uses of it left.
432 if (Operand->use_empty())
433 DeadNodes.push_back(Operand);
435 if (N->OperandsNeedDelete)
436 delete[] N->OperandList;
440 // Finally, remove N itself.
444 // If the root changed (e.g. it was a dead load, update the root).
445 setRoot(Dummy.getValue());
448 void SelectionDAG::RemoveDeadNode(SDNode *N, std::vector<SDNode*> &Deleted) {
449 SmallVector<SDNode*, 16> DeadNodes;
450 DeadNodes.push_back(N);
452 // Process the worklist, deleting the nodes and adding their uses to the
454 while (!DeadNodes.empty()) {
455 SDNode *N = DeadNodes.back();
456 DeadNodes.pop_back();
458 // Take the node out of the appropriate CSE map.
459 RemoveNodeFromCSEMaps(N);
461 // Next, brutally remove the operand list. This is safe to do, as there are
462 // no cycles in the graph.
463 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
464 SDNode *Operand = I->Val;
465 Operand->removeUser(N);
467 // Now that we removed this operand, see if there are no uses of it left.
468 if (Operand->use_empty())
469 DeadNodes.push_back(Operand);
471 if (N->OperandsNeedDelete)
472 delete[] N->OperandList;
476 // Finally, remove N itself.
477 Deleted.push_back(N);
482 void SelectionDAG::DeleteNode(SDNode *N) {
483 assert(N->use_empty() && "Cannot delete a node that is not dead!");
485 // First take this out of the appropriate CSE map.
486 RemoveNodeFromCSEMaps(N);
488 // Finally, remove uses due to operands of this node, remove from the
489 // AllNodes list, and delete the node.
490 DeleteNodeNotInCSEMaps(N);
493 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
495 // Remove it from the AllNodes list.
498 // Drop all of the operands and decrement used nodes use counts.
499 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I)
500 I->Val->removeUser(N);
501 if (N->OperandsNeedDelete)
502 delete[] N->OperandList;
509 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
510 /// correspond to it. This is useful when we're about to delete or repurpose
511 /// the node. We don't want future request for structurally identical nodes
512 /// to return N anymore.
513 void SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
515 switch (N->getOpcode()) {
516 case ISD::HANDLENODE: return; // noop.
518 Erased = StringNodes.erase(cast<StringSDNode>(N)->getValue());
521 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
522 "Cond code doesn't exist!");
523 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != 0;
524 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = 0;
526 case ISD::ExternalSymbol:
527 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
529 case ISD::TargetExternalSymbol:
531 TargetExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
533 case ISD::VALUETYPE: {
534 MVT::ValueType VT = cast<VTSDNode>(N)->getVT();
535 if (MVT::isExtendedVT(VT)) {
536 Erased = ExtendedValueTypeNodes.erase(VT);
538 Erased = ValueTypeNodes[VT] != 0;
539 ValueTypeNodes[VT] = 0;
544 // Remove it from the CSE Map.
545 Erased = CSEMap.RemoveNode(N);
549 // Verify that the node was actually in one of the CSE maps, unless it has a
550 // flag result (which cannot be CSE'd) or is one of the special cases that are
551 // not subject to CSE.
552 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Flag &&
553 !N->isTargetOpcode()) {
556 assert(0 && "Node is not in map!");
561 /// AddNonLeafNodeToCSEMaps - Add the specified node back to the CSE maps. It
562 /// has been taken out and modified in some way. If the specified node already
563 /// exists in the CSE maps, do not modify the maps, but return the existing node
564 /// instead. If it doesn't exist, add it and return null.
566 SDNode *SelectionDAG::AddNonLeafNodeToCSEMaps(SDNode *N) {
567 assert(N->getNumOperands() && "This is a leaf node!");
568 if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
569 return 0; // Never add these nodes.
571 // Check that remaining values produced are not flags.
572 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
573 if (N->getValueType(i) == MVT::Flag)
574 return 0; // Never CSE anything that produces a flag.
576 SDNode *New = CSEMap.GetOrInsertNode(N);
577 if (New != N) return New; // Node already existed.
581 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
582 /// were replaced with those specified. If this node is never memoized,
583 /// return null, otherwise return a pointer to the slot it would take. If a
584 /// node already exists with these operands, the slot will be non-null.
585 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDOperand Op,
587 if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
588 return 0; // Never add these nodes.
590 // Check that remaining values produced are not flags.
591 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
592 if (N->getValueType(i) == MVT::Flag)
593 return 0; // Never CSE anything that produces a flag.
595 SDOperand Ops[] = { Op };
597 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 1);
598 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
601 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
602 /// were replaced with those specified. If this node is never memoized,
603 /// return null, otherwise return a pointer to the slot it would take. If a
604 /// node already exists with these operands, the slot will be non-null.
605 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
606 SDOperand Op1, SDOperand Op2,
608 if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
609 return 0; // Never add these nodes.
611 // Check that remaining values produced are not flags.
612 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
613 if (N->getValueType(i) == MVT::Flag)
614 return 0; // Never CSE anything that produces a flag.
616 SDOperand Ops[] = { Op1, Op2 };
618 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 2);
619 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
623 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
624 /// were replaced with those specified. If this node is never memoized,
625 /// return null, otherwise return a pointer to the slot it would take. If a
626 /// node already exists with these operands, the slot will be non-null.
627 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
628 const SDOperand *Ops,unsigned NumOps,
630 if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
631 return 0; // Never add these nodes.
633 // Check that remaining values produced are not flags.
634 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
635 if (N->getValueType(i) == MVT::Flag)
636 return 0; // Never CSE anything that produces a flag.
639 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, NumOps);
641 if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
642 ID.AddInteger(LD->getAddressingMode());
643 ID.AddInteger(LD->getExtensionType());
644 ID.AddInteger((unsigned int)(LD->getMemoryVT()));
645 ID.AddInteger(LD->getAlignment());
646 ID.AddInteger(LD->isVolatile());
647 } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
648 ID.AddInteger(ST->getAddressingMode());
649 ID.AddInteger(ST->isTruncatingStore());
650 ID.AddInteger((unsigned int)(ST->getMemoryVT()));
651 ID.AddInteger(ST->getAlignment());
652 ID.AddInteger(ST->isVolatile());
655 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
659 SelectionDAG::~SelectionDAG() {
660 while (!AllNodes.empty()) {
661 SDNode *N = AllNodes.begin();
662 N->SetNextInBucket(0);
663 if (N->OperandsNeedDelete)
664 delete [] N->OperandList;
667 AllNodes.pop_front();
671 SDOperand SelectionDAG::getZeroExtendInReg(SDOperand Op, MVT::ValueType VT) {
672 if (Op.getValueType() == VT) return Op;
673 int64_t Imm = ~0ULL >> (64-MVT::getSizeInBits(VT));
674 return getNode(ISD::AND, Op.getValueType(), Op,
675 getConstant(Imm, Op.getValueType()));
678 SDOperand SelectionDAG::getString(const std::string &Val) {
679 StringSDNode *&N = StringNodes[Val];
681 N = new StringSDNode(Val);
682 AllNodes.push_back(N);
684 return SDOperand(N, 0);
687 SDOperand SelectionDAG::getConstant(uint64_t Val, MVT::ValueType VT, bool isT) {
688 assert(MVT::isInteger(VT) && "Cannot create FP integer constant!");
690 MVT::ValueType EltVT =
691 MVT::isVector(VT) ? MVT::getVectorElementType(VT) : VT;
693 // Mask out any bits that are not valid for this constant.
694 Val &= MVT::getIntVTBitMask(EltVT);
696 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
698 AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0);
702 if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
703 if (!MVT::isVector(VT))
704 return SDOperand(N, 0);
706 N = new ConstantSDNode(isT, Val, EltVT);
707 CSEMap.InsertNode(N, IP);
708 AllNodes.push_back(N);
711 SDOperand Result(N, 0);
712 if (MVT::isVector(VT)) {
713 SmallVector<SDOperand, 8> Ops;
714 Ops.assign(MVT::getVectorNumElements(VT), Result);
715 Result = getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
720 SDOperand SelectionDAG::getIntPtrConstant(uint64_t Val, bool isTarget) {
721 return getConstant(Val, TLI.getPointerTy(), isTarget);
725 SDOperand SelectionDAG::getConstantFP(const APFloat& V, MVT::ValueType VT,
727 assert(MVT::isFloatingPoint(VT) && "Cannot create integer FP constant!");
729 MVT::ValueType EltVT =
730 MVT::isVector(VT) ? MVT::getVectorElementType(VT) : VT;
732 // Do the map lookup using the actual bit pattern for the floating point
733 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
734 // we don't have issues with SNANs.
735 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
737 AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0);
741 if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
742 if (!MVT::isVector(VT))
743 return SDOperand(N, 0);
745 N = new ConstantFPSDNode(isTarget, V, EltVT);
746 CSEMap.InsertNode(N, IP);
747 AllNodes.push_back(N);
750 SDOperand Result(N, 0);
751 if (MVT::isVector(VT)) {
752 SmallVector<SDOperand, 8> Ops;
753 Ops.assign(MVT::getVectorNumElements(VT), Result);
754 Result = getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
759 SDOperand SelectionDAG::getConstantFP(double Val, MVT::ValueType VT,
761 MVT::ValueType EltVT =
762 MVT::isVector(VT) ? MVT::getVectorElementType(VT) : VT;
764 return getConstantFP(APFloat((float)Val), VT, isTarget);
766 return getConstantFP(APFloat(Val), VT, isTarget);
769 SDOperand SelectionDAG::getGlobalAddress(const GlobalValue *GV,
770 MVT::ValueType VT, int Offset,
772 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
774 if (GVar && GVar->isThreadLocal())
775 Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
777 Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
779 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
781 ID.AddInteger(Offset);
783 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
784 return SDOperand(E, 0);
785 SDNode *N = new GlobalAddressSDNode(isTargetGA, GV, VT, Offset);
786 CSEMap.InsertNode(N, IP);
787 AllNodes.push_back(N);
788 return SDOperand(N, 0);
791 SDOperand SelectionDAG::getFrameIndex(int FI, MVT::ValueType VT,
793 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
795 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
798 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
799 return SDOperand(E, 0);
800 SDNode *N = new FrameIndexSDNode(FI, VT, isTarget);
801 CSEMap.InsertNode(N, IP);
802 AllNodes.push_back(N);
803 return SDOperand(N, 0);
806 SDOperand SelectionDAG::getJumpTable(int JTI, MVT::ValueType VT, bool isTarget){
807 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
809 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
812 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
813 return SDOperand(E, 0);
814 SDNode *N = new JumpTableSDNode(JTI, VT, isTarget);
815 CSEMap.InsertNode(N, IP);
816 AllNodes.push_back(N);
817 return SDOperand(N, 0);
820 SDOperand SelectionDAG::getConstantPool(Constant *C, MVT::ValueType VT,
821 unsigned Alignment, int Offset,
823 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
825 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
826 ID.AddInteger(Alignment);
827 ID.AddInteger(Offset);
830 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
831 return SDOperand(E, 0);
832 SDNode *N = new ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment);
833 CSEMap.InsertNode(N, IP);
834 AllNodes.push_back(N);
835 return SDOperand(N, 0);
839 SDOperand SelectionDAG::getConstantPool(MachineConstantPoolValue *C,
841 unsigned Alignment, int Offset,
843 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
845 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
846 ID.AddInteger(Alignment);
847 ID.AddInteger(Offset);
848 C->AddSelectionDAGCSEId(ID);
850 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
851 return SDOperand(E, 0);
852 SDNode *N = new ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment);
853 CSEMap.InsertNode(N, IP);
854 AllNodes.push_back(N);
855 return SDOperand(N, 0);
859 SDOperand SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
861 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), 0, 0);
864 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
865 return SDOperand(E, 0);
866 SDNode *N = new BasicBlockSDNode(MBB);
867 CSEMap.InsertNode(N, IP);
868 AllNodes.push_back(N);
869 return SDOperand(N, 0);
872 SDOperand SelectionDAG::getValueType(MVT::ValueType VT) {
873 if (!MVT::isExtendedVT(VT) && (unsigned)VT >= ValueTypeNodes.size())
874 ValueTypeNodes.resize(VT+1);
876 SDNode *&N = MVT::isExtendedVT(VT) ?
877 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT];
879 if (N) return SDOperand(N, 0);
880 N = new VTSDNode(VT);
881 AllNodes.push_back(N);
882 return SDOperand(N, 0);
885 SDOperand SelectionDAG::getExternalSymbol(const char *Sym, MVT::ValueType VT) {
886 SDNode *&N = ExternalSymbols[Sym];
887 if (N) return SDOperand(N, 0);
888 N = new ExternalSymbolSDNode(false, Sym, VT);
889 AllNodes.push_back(N);
890 return SDOperand(N, 0);
893 SDOperand SelectionDAG::getTargetExternalSymbol(const char *Sym,
895 SDNode *&N = TargetExternalSymbols[Sym];
896 if (N) return SDOperand(N, 0);
897 N = new ExternalSymbolSDNode(true, Sym, VT);
898 AllNodes.push_back(N);
899 return SDOperand(N, 0);
902 SDOperand SelectionDAG::getCondCode(ISD::CondCode Cond) {
903 if ((unsigned)Cond >= CondCodeNodes.size())
904 CondCodeNodes.resize(Cond+1);
906 if (CondCodeNodes[Cond] == 0) {
907 CondCodeNodes[Cond] = new CondCodeSDNode(Cond);
908 AllNodes.push_back(CondCodeNodes[Cond]);
910 return SDOperand(CondCodeNodes[Cond], 0);
913 SDOperand SelectionDAG::getRegister(unsigned RegNo, MVT::ValueType VT) {
915 AddNodeIDNode(ID, ISD::Register, getVTList(VT), 0, 0);
916 ID.AddInteger(RegNo);
918 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
919 return SDOperand(E, 0);
920 SDNode *N = new RegisterSDNode(RegNo, VT);
921 CSEMap.InsertNode(N, IP);
922 AllNodes.push_back(N);
923 return SDOperand(N, 0);
926 SDOperand SelectionDAG::getSrcValue(const Value *V) {
927 assert((!V || isa<PointerType>(V->getType())) &&
928 "SrcValue is not a pointer?");
931 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), 0, 0);
935 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
936 return SDOperand(E, 0);
938 SDNode *N = new SrcValueSDNode(V);
939 CSEMap.InsertNode(N, IP);
940 AllNodes.push_back(N);
941 return SDOperand(N, 0);
944 SDOperand SelectionDAG::getMemOperand(const MemOperand &MO) {
945 const Value *v = MO.getValue();
946 assert((!v || isa<PointerType>(v->getType())) &&
947 "SrcValue is not a pointer?");
950 AddNodeIDNode(ID, ISD::MEMOPERAND, getVTList(MVT::Other), 0, 0);
952 ID.AddInteger(MO.getFlags());
953 ID.AddInteger(MO.getOffset());
954 ID.AddInteger(MO.getSize());
955 ID.AddInteger(MO.getAlignment());
958 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
959 return SDOperand(E, 0);
961 SDNode *N = new MemOperandSDNode(MO);
962 CSEMap.InsertNode(N, IP);
963 AllNodes.push_back(N);
964 return SDOperand(N, 0);
967 /// CreateStackTemporary - Create a stack temporary, suitable for holding the
968 /// specified value type.
969 SDOperand SelectionDAG::CreateStackTemporary(MVT::ValueType VT) {
970 MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo();
971 unsigned ByteSize = MVT::getSizeInBits(VT)/8;
972 const Type *Ty = MVT::getTypeForValueType(VT);
973 unsigned StackAlign = (unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty);
974 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign);
975 return getFrameIndex(FrameIdx, TLI.getPointerTy());
979 SDOperand SelectionDAG::FoldSetCC(MVT::ValueType VT, SDOperand N1,
980 SDOperand N2, ISD::CondCode Cond) {
981 // These setcc operations always fold.
985 case ISD::SETFALSE2: return getConstant(0, VT);
987 case ISD::SETTRUE2: return getConstant(1, VT);
999 assert(!MVT::isInteger(N1.getValueType()) && "Illegal setcc for integer!");
1003 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val)) {
1004 uint64_t C2 = N2C->getValue();
1005 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val)) {
1006 uint64_t C1 = N1C->getValue();
1008 // Sign extend the operands if required
1009 if (ISD::isSignedIntSetCC(Cond)) {
1010 C1 = N1C->getSignExtended();
1011 C2 = N2C->getSignExtended();
1015 default: assert(0 && "Unknown integer setcc!");
1016 case ISD::SETEQ: return getConstant(C1 == C2, VT);
1017 case ISD::SETNE: return getConstant(C1 != C2, VT);
1018 case ISD::SETULT: return getConstant(C1 < C2, VT);
1019 case ISD::SETUGT: return getConstant(C1 > C2, VT);
1020 case ISD::SETULE: return getConstant(C1 <= C2, VT);
1021 case ISD::SETUGE: return getConstant(C1 >= C2, VT);
1022 case ISD::SETLT: return getConstant((int64_t)C1 < (int64_t)C2, VT);
1023 case ISD::SETGT: return getConstant((int64_t)C1 > (int64_t)C2, VT);
1024 case ISD::SETLE: return getConstant((int64_t)C1 <= (int64_t)C2, VT);
1025 case ISD::SETGE: return getConstant((int64_t)C1 >= (int64_t)C2, VT);
1029 if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1.Val))
1030 if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2.Val)) {
1031 // No compile time operations on this type yet.
1032 if (N1C->getValueType(0) == MVT::ppcf128)
1035 APFloat::cmpResult R = N1C->getValueAPF().compare(N2C->getValueAPF());
1038 case ISD::SETEQ: if (R==APFloat::cmpUnordered)
1039 return getNode(ISD::UNDEF, VT);
1041 case ISD::SETOEQ: return getConstant(R==APFloat::cmpEqual, VT);
1042 case ISD::SETNE: if (R==APFloat::cmpUnordered)
1043 return getNode(ISD::UNDEF, VT);
1045 case ISD::SETONE: return getConstant(R==APFloat::cmpGreaterThan ||
1046 R==APFloat::cmpLessThan, VT);
1047 case ISD::SETLT: if (R==APFloat::cmpUnordered)
1048 return getNode(ISD::UNDEF, VT);
1050 case ISD::SETOLT: return getConstant(R==APFloat::cmpLessThan, VT);
1051 case ISD::SETGT: if (R==APFloat::cmpUnordered)
1052 return getNode(ISD::UNDEF, VT);
1054 case ISD::SETOGT: return getConstant(R==APFloat::cmpGreaterThan, VT);
1055 case ISD::SETLE: if (R==APFloat::cmpUnordered)
1056 return getNode(ISD::UNDEF, VT);
1058 case ISD::SETOLE: return getConstant(R==APFloat::cmpLessThan ||
1059 R==APFloat::cmpEqual, VT);
1060 case ISD::SETGE: if (R==APFloat::cmpUnordered)
1061 return getNode(ISD::UNDEF, VT);
1063 case ISD::SETOGE: return getConstant(R==APFloat::cmpGreaterThan ||
1064 R==APFloat::cmpEqual, VT);
1065 case ISD::SETO: return getConstant(R!=APFloat::cmpUnordered, VT);
1066 case ISD::SETUO: return getConstant(R==APFloat::cmpUnordered, VT);
1067 case ISD::SETUEQ: return getConstant(R==APFloat::cmpUnordered ||
1068 R==APFloat::cmpEqual, VT);
1069 case ISD::SETUNE: return getConstant(R!=APFloat::cmpEqual, VT);
1070 case ISD::SETULT: return getConstant(R==APFloat::cmpUnordered ||
1071 R==APFloat::cmpLessThan, VT);
1072 case ISD::SETUGT: return getConstant(R==APFloat::cmpGreaterThan ||
1073 R==APFloat::cmpUnordered, VT);
1074 case ISD::SETULE: return getConstant(R!=APFloat::cmpGreaterThan, VT);
1075 case ISD::SETUGE: return getConstant(R!=APFloat::cmpLessThan, VT);
1078 // Ensure that the constant occurs on the RHS.
1079 return getSetCC(VT, N2, N1, ISD::getSetCCSwappedOperands(Cond));
1082 // Could not fold it.
1086 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1087 /// this predicate to simplify operations downstream. Mask is known to be zero
1088 /// for bits that V cannot have.
1089 bool SelectionDAG::MaskedValueIsZero(SDOperand Op, uint64_t Mask,
1090 unsigned Depth) const {
1091 // The masks are not wide enough to represent this type! Should use APInt.
1092 if (Op.getValueType() == MVT::i128)
1095 uint64_t KnownZero, KnownOne;
1096 ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
1097 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1098 return (KnownZero & Mask) == Mask;
1101 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
1102 /// known to be either zero or one and return them in the KnownZero/KnownOne
1103 /// bitsets. This code only analyzes bits in Mask, in order to short-circuit
1105 void SelectionDAG::ComputeMaskedBits(SDOperand Op, uint64_t Mask,
1106 uint64_t &KnownZero, uint64_t &KnownOne,
1107 unsigned Depth) const {
1108 KnownZero = KnownOne = 0; // Don't know anything.
1109 if (Depth == 6 || Mask == 0)
1110 return; // Limit search depth.
1112 // The masks are not wide enough to represent this type! Should use APInt.
1113 if (Op.getValueType() == MVT::i128)
1116 uint64_t KnownZero2, KnownOne2;
1118 switch (Op.getOpcode()) {
1120 // We know all of the bits for a constant!
1121 KnownOne = cast<ConstantSDNode>(Op)->getValue() & Mask;
1122 KnownZero = ~KnownOne & Mask;
1125 // If either the LHS or the RHS are Zero, the result is zero.
1126 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1128 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
1129 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1130 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1132 // Output known-1 bits are only known if set in both the LHS & RHS.
1133 KnownOne &= KnownOne2;
1134 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1135 KnownZero |= KnownZero2;
1138 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1140 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
1141 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1142 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1144 // Output known-0 bits are only known if clear in both the LHS & RHS.
1145 KnownZero &= KnownZero2;
1146 // Output known-1 are known to be set if set in either the LHS | RHS.
1147 KnownOne |= KnownOne2;
1150 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1151 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
1152 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1153 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1155 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1156 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
1157 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1158 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
1159 KnownZero = KnownZeroOut;
1163 ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
1164 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
1165 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1166 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1168 // Only known if known in both the LHS and RHS.
1169 KnownOne &= KnownOne2;
1170 KnownZero &= KnownZero2;
1172 case ISD::SELECT_CC:
1173 ComputeMaskedBits(Op.getOperand(3), Mask, KnownZero, KnownOne, Depth+1);
1174 ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero2, KnownOne2, Depth+1);
1175 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1176 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1178 // Only known if known in both the LHS and RHS.
1179 KnownOne &= KnownOne2;
1180 KnownZero &= KnownZero2;
1183 // If we know the result of a setcc has the top bits zero, use this info.
1184 if (TLI.getSetCCResultContents() == TargetLowering::ZeroOrOneSetCCResult)
1185 KnownZero |= (MVT::getIntVTBitMask(Op.getValueType()) ^ 1ULL);
1188 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
1189 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1190 ComputeMaskedBits(Op.getOperand(0), Mask >> SA->getValue(),
1191 KnownZero, KnownOne, Depth+1);
1192 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1193 KnownZero <<= SA->getValue();
1194 KnownOne <<= SA->getValue();
1195 KnownZero |= (1ULL << SA->getValue())-1; // low bits known zero.
1199 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
1200 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1201 MVT::ValueType VT = Op.getValueType();
1202 unsigned ShAmt = SA->getValue();
1204 uint64_t TypeMask = MVT::getIntVTBitMask(VT);
1205 ComputeMaskedBits(Op.getOperand(0), (Mask << ShAmt) & TypeMask,
1206 KnownZero, KnownOne, Depth+1);
1207 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1208 KnownZero &= TypeMask;
1209 KnownOne &= TypeMask;
1210 KnownZero >>= ShAmt;
1213 uint64_t HighBits = (1ULL << ShAmt)-1;
1214 HighBits <<= MVT::getSizeInBits(VT)-ShAmt;
1215 KnownZero |= HighBits; // High bits known zero.
1219 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1220 MVT::ValueType VT = Op.getValueType();
1221 unsigned ShAmt = SA->getValue();
1223 // Compute the new bits that are at the top now.
1224 uint64_t TypeMask = MVT::getIntVTBitMask(VT);
1226 uint64_t InDemandedMask = (Mask << ShAmt) & TypeMask;
1227 // If any of the demanded bits are produced by the sign extension, we also
1228 // demand the input sign bit.
1229 uint64_t HighBits = (1ULL << ShAmt)-1;
1230 HighBits <<= MVT::getSizeInBits(VT) - ShAmt;
1231 if (HighBits & Mask)
1232 InDemandedMask |= MVT::getIntVTSignBit(VT);
1234 ComputeMaskedBits(Op.getOperand(0), InDemandedMask, KnownZero, KnownOne,
1236 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1237 KnownZero &= TypeMask;
1238 KnownOne &= TypeMask;
1239 KnownZero >>= ShAmt;
1242 // Handle the sign bits.
1243 uint64_t SignBit = MVT::getIntVTSignBit(VT);
1244 SignBit >>= ShAmt; // Adjust to where it is now in the mask.
1246 if (KnownZero & SignBit) {
1247 KnownZero |= HighBits; // New bits are known zero.
1248 } else if (KnownOne & SignBit) {
1249 KnownOne |= HighBits; // New bits are known one.
1253 case ISD::SIGN_EXTEND_INREG: {
1254 MVT::ValueType EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1256 // Sign extension. Compute the demanded bits in the result that are not
1257 // present in the input.
1258 uint64_t NewBits = ~MVT::getIntVTBitMask(EVT) & Mask;
1260 uint64_t InSignBit = MVT::getIntVTSignBit(EVT);
1261 int64_t InputDemandedBits = Mask & MVT::getIntVTBitMask(EVT);
1263 // If the sign extended bits are demanded, we know that the sign
1266 InputDemandedBits |= InSignBit;
1268 ComputeMaskedBits(Op.getOperand(0), InputDemandedBits,
1269 KnownZero, KnownOne, Depth+1);
1270 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1272 // If the sign bit of the input is known set or clear, then we know the
1273 // top bits of the result.
1274 if (KnownZero & InSignBit) { // Input sign bit known clear
1275 KnownZero |= NewBits;
1276 KnownOne &= ~NewBits;
1277 } else if (KnownOne & InSignBit) { // Input sign bit known set
1278 KnownOne |= NewBits;
1279 KnownZero &= ~NewBits;
1280 } else { // Input sign bit unknown
1281 KnownZero &= ~NewBits;
1282 KnownOne &= ~NewBits;
1289 MVT::ValueType VT = Op.getValueType();
1290 unsigned LowBits = Log2_32(MVT::getSizeInBits(VT))+1;
1291 KnownZero = ~((1ULL << LowBits)-1) & MVT::getIntVTBitMask(VT);
1296 if (ISD::isZEXTLoad(Op.Val)) {
1297 LoadSDNode *LD = cast<LoadSDNode>(Op);
1298 MVT::ValueType VT = LD->getMemoryVT();
1299 KnownZero |= ~MVT::getIntVTBitMask(VT) & Mask;
1303 case ISD::ZERO_EXTEND: {
1304 uint64_t InMask = MVT::getIntVTBitMask(Op.getOperand(0).getValueType());
1305 uint64_t NewBits = (~InMask) & Mask;
1306 ComputeMaskedBits(Op.getOperand(0), Mask & InMask, KnownZero,
1308 KnownZero |= NewBits & Mask;
1309 KnownOne &= ~NewBits;
1312 case ISD::SIGN_EXTEND: {
1313 MVT::ValueType InVT = Op.getOperand(0).getValueType();
1314 unsigned InBits = MVT::getSizeInBits(InVT);
1315 uint64_t InMask = MVT::getIntVTBitMask(InVT);
1316 uint64_t InSignBit = 1ULL << (InBits-1);
1317 uint64_t NewBits = (~InMask) & Mask;
1318 uint64_t InDemandedBits = Mask & InMask;
1320 // If any of the sign extended bits are demanded, we know that the sign
1323 InDemandedBits |= InSignBit;
1325 ComputeMaskedBits(Op.getOperand(0), InDemandedBits, KnownZero,
1327 // If the sign bit is known zero or one, the top bits match.
1328 if (KnownZero & InSignBit) {
1329 KnownZero |= NewBits;
1330 KnownOne &= ~NewBits;
1331 } else if (KnownOne & InSignBit) {
1332 KnownOne |= NewBits;
1333 KnownZero &= ~NewBits;
1334 } else { // Otherwise, top bits aren't known.
1335 KnownOne &= ~NewBits;
1336 KnownZero &= ~NewBits;
1340 case ISD::ANY_EXTEND: {
1341 MVT::ValueType VT = Op.getOperand(0).getValueType();
1342 ComputeMaskedBits(Op.getOperand(0), Mask & MVT::getIntVTBitMask(VT),
1343 KnownZero, KnownOne, Depth+1);
1346 case ISD::TRUNCATE: {
1347 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
1348 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1349 uint64_t OutMask = MVT::getIntVTBitMask(Op.getValueType());
1350 KnownZero &= OutMask;
1351 KnownOne &= OutMask;
1354 case ISD::AssertZext: {
1355 MVT::ValueType VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1356 uint64_t InMask = MVT::getIntVTBitMask(VT);
1357 ComputeMaskedBits(Op.getOperand(0), Mask & InMask, KnownZero,
1359 KnownZero |= (~InMask) & Mask;
1363 // All bits are zero except the low bit.
1364 KnownZero = MVT::getIntVTBitMask(Op.getValueType()) ^ 1;
1368 // If either the LHS or the RHS are Zero, the result is zero.
1369 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1370 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
1371 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1372 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1374 // Output known-0 bits are known if clear or set in both the low clear bits
1375 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
1376 // low 3 bits clear.
1377 uint64_t KnownZeroOut = std::min(CountTrailingZeros_64(~KnownZero),
1378 CountTrailingZeros_64(~KnownZero2));
1380 KnownZero = (1ULL << KnownZeroOut) - 1;
1385 ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0));
1388 // We know that the top bits of C-X are clear if X contains less bits
1389 // than C (i.e. no wrap-around can happen). For example, 20-X is
1390 // positive if we can prove that X is >= 0 and < 16.
1391 MVT::ValueType VT = CLHS->getValueType(0);
1392 if ((CLHS->getValue() & MVT::getIntVTSignBit(VT)) == 0) { // sign bit clear
1393 unsigned NLZ = CountLeadingZeros_64(CLHS->getValue()+1);
1394 uint64_t MaskV = (1ULL << (63-NLZ))-1; // NLZ can't be 64 with no sign bit
1395 MaskV = ~MaskV & MVT::getIntVTBitMask(VT);
1396 ComputeMaskedBits(Op.getOperand(1), MaskV, KnownZero, KnownOne, Depth+1);
1398 // If all of the MaskV bits are known to be zero, then we know the output
1399 // top bits are zero, because we now know that the output is from [0-C].
1400 if ((KnownZero & MaskV) == MaskV) {
1401 unsigned NLZ2 = CountLeadingZeros_64(CLHS->getValue());
1402 KnownZero = ~((1ULL << (64-NLZ2))-1) & Mask; // Top bits known zero.
1403 KnownOne = 0; // No one bits known.
1405 KnownZero = KnownOne = 0; // Otherwise, nothing known.
1411 // Allow the target to implement this method for its nodes.
1412 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) {
1413 case ISD::INTRINSIC_WO_CHAIN:
1414 case ISD::INTRINSIC_W_CHAIN:
1415 case ISD::INTRINSIC_VOID:
1416 TLI.computeMaskedBitsForTargetNode(Op, Mask, KnownZero, KnownOne, *this);
1422 /// ComputeNumSignBits - Return the number of times the sign bit of the
1423 /// register is replicated into the other bits. We know that at least 1 bit
1424 /// is always equal to the sign bit (itself), but other cases can give us
1425 /// information. For example, immediately after an "SRA X, 2", we know that
1426 /// the top 3 bits are all equal to each other, so we return 3.
1427 unsigned SelectionDAG::ComputeNumSignBits(SDOperand Op, unsigned Depth) const{
1428 MVT::ValueType VT = Op.getValueType();
1429 assert(MVT::isInteger(VT) && "Invalid VT!");
1430 unsigned VTBits = MVT::getSizeInBits(VT);
1434 return 1; // Limit search depth.
1436 switch (Op.getOpcode()) {
1438 case ISD::AssertSext:
1439 Tmp = MVT::getSizeInBits(cast<VTSDNode>(Op.getOperand(1))->getVT());
1440 return VTBits-Tmp+1;
1441 case ISD::AssertZext:
1442 Tmp = MVT::getSizeInBits(cast<VTSDNode>(Op.getOperand(1))->getVT());
1445 case ISD::Constant: {
1446 uint64_t Val = cast<ConstantSDNode>(Op)->getValue();
1447 // If negative, invert the bits, then look at it.
1448 if (Val & MVT::getIntVTSignBit(VT))
1451 // Shift the bits so they are the leading bits in the int64_t.
1454 // Return # leading zeros. We use 'min' here in case Val was zero before
1455 // shifting. We don't want to return '64' as for an i32 "0".
1456 return std::min(VTBits, CountLeadingZeros_64(Val));
1459 case ISD::SIGN_EXTEND:
1460 Tmp = VTBits-MVT::getSizeInBits(Op.getOperand(0).getValueType());
1461 return ComputeNumSignBits(Op.getOperand(0), Depth+1) + Tmp;
1463 case ISD::SIGN_EXTEND_INREG:
1464 // Max of the input and what this extends.
1465 Tmp = MVT::getSizeInBits(cast<VTSDNode>(Op.getOperand(1))->getVT());
1468 Tmp2 = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1469 return std::max(Tmp, Tmp2);
1472 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1473 // SRA X, C -> adds C sign bits.
1474 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1475 Tmp += C->getValue();
1476 if (Tmp > VTBits) Tmp = VTBits;
1480 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1481 // shl destroys sign bits.
1482 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1483 if (C->getValue() >= VTBits || // Bad shift.
1484 C->getValue() >= Tmp) break; // Shifted all sign bits out.
1485 return Tmp - C->getValue();
1490 case ISD::XOR: // NOT is handled here.
1491 // Logical binary ops preserve the number of sign bits.
1492 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1493 if (Tmp == 1) return 1; // Early out.
1494 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1495 return std::min(Tmp, Tmp2);
1498 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1499 if (Tmp == 1) return 1; // Early out.
1500 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1501 return std::min(Tmp, Tmp2);
1504 // If setcc returns 0/-1, all bits are sign bits.
1505 if (TLI.getSetCCResultContents() ==
1506 TargetLowering::ZeroOrNegativeOneSetCCResult)
1511 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1512 unsigned RotAmt = C->getValue() & (VTBits-1);
1514 // Handle rotate right by N like a rotate left by 32-N.
1515 if (Op.getOpcode() == ISD::ROTR)
1516 RotAmt = (VTBits-RotAmt) & (VTBits-1);
1518 // If we aren't rotating out all of the known-in sign bits, return the
1519 // number that are left. This handles rotl(sext(x), 1) for example.
1520 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1521 if (Tmp > RotAmt+1) return Tmp-RotAmt;
1525 // Add can have at most one carry bit. Thus we know that the output
1526 // is, at worst, one more bit than the inputs.
1527 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1528 if (Tmp == 1) return 1; // Early out.
1530 // Special case decrementing a value (ADD X, -1):
1531 if (ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
1532 if (CRHS->isAllOnesValue()) {
1533 uint64_t KnownZero, KnownOne;
1534 uint64_t Mask = MVT::getIntVTBitMask(VT);
1535 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
1537 // If the input is known to be 0 or 1, the output is 0/-1, which is all
1539 if ((KnownZero|1) == Mask)
1542 // If we are subtracting one from a positive number, there is no carry
1543 // out of the result.
1544 if (KnownZero & MVT::getIntVTSignBit(VT))
1548 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1549 if (Tmp2 == 1) return 1;
1550 return std::min(Tmp, Tmp2)-1;
1554 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1555 if (Tmp2 == 1) return 1;
1558 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
1559 if (CLHS->getValue() == 0) {
1560 uint64_t KnownZero, KnownOne;
1561 uint64_t Mask = MVT::getIntVTBitMask(VT);
1562 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1563 // If the input is known to be 0 or 1, the output is 0/-1, which is all
1565 if ((KnownZero|1) == Mask)
1568 // If the input is known to be positive (the sign bit is known clear),
1569 // the output of the NEG has the same number of sign bits as the input.
1570 if (KnownZero & MVT::getIntVTSignBit(VT))
1573 // Otherwise, we treat this like a SUB.
1576 // Sub can have at most one carry bit. Thus we know that the output
1577 // is, at worst, one more bit than the inputs.
1578 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1579 if (Tmp == 1) return 1; // Early out.
1580 return std::min(Tmp, Tmp2)-1;
1583 // FIXME: it's tricky to do anything useful for this, but it is an important
1584 // case for targets like X86.
1588 // Handle LOADX separately here. EXTLOAD case will fallthrough.
1589 if (Op.getOpcode() == ISD::LOAD) {
1590 LoadSDNode *LD = cast<LoadSDNode>(Op);
1591 unsigned ExtType = LD->getExtensionType();
1594 case ISD::SEXTLOAD: // '17' bits known
1595 Tmp = MVT::getSizeInBits(LD->getMemoryVT());
1596 return VTBits-Tmp+1;
1597 case ISD::ZEXTLOAD: // '16' bits known
1598 Tmp = MVT::getSizeInBits(LD->getMemoryVT());
1603 // Allow the target to implement this method for its nodes.
1604 if (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
1605 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1606 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
1607 Op.getOpcode() == ISD::INTRINSIC_VOID) {
1608 unsigned NumBits = TLI.ComputeNumSignBitsForTargetNode(Op, Depth);
1609 if (NumBits > 1) return NumBits;
1612 // Finally, if we can prove that the top bits of the result are 0's or 1's,
1613 // use this information.
1614 uint64_t KnownZero, KnownOne;
1615 uint64_t Mask = MVT::getIntVTBitMask(VT);
1616 ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
1618 uint64_t SignBit = MVT::getIntVTSignBit(VT);
1619 if (KnownZero & SignBit) { // SignBit is 0
1621 } else if (KnownOne & SignBit) { // SignBit is 1;
1628 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
1629 // the number of identical bits in the top of the input value.
1632 // Return # leading zeros. We use 'min' here in case Val was zero before
1633 // shifting. We don't want to return '64' as for an i32 "0".
1634 return std::min(VTBits, CountLeadingZeros_64(Mask));
1638 /// getNode - Gets or creates the specified node.
1640 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT) {
1641 FoldingSetNodeID ID;
1642 AddNodeIDNode(ID, Opcode, getVTList(VT), 0, 0);
1644 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1645 return SDOperand(E, 0);
1646 SDNode *N = new SDNode(Opcode, SDNode::getSDVTList(VT));
1647 CSEMap.InsertNode(N, IP);
1649 AllNodes.push_back(N);
1650 return SDOperand(N, 0);
1653 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
1654 SDOperand Operand) {
1656 // Constant fold unary operations with an integer constant operand.
1657 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand.Val)) {
1658 uint64_t Val = C->getValue();
1661 case ISD::SIGN_EXTEND: return getConstant(C->getSignExtended(), VT);
1662 case ISD::ANY_EXTEND:
1663 case ISD::ZERO_EXTEND: return getConstant(Val, VT);
1664 case ISD::TRUNCATE: return getConstant(Val, VT);
1665 case ISD::UINT_TO_FP:
1666 case ISD::SINT_TO_FP: {
1667 const uint64_t zero[] = {0, 0};
1668 // No compile time operations on this type.
1669 if (VT==MVT::ppcf128)
1671 APFloat apf = APFloat(APInt(MVT::getSizeInBits(VT), 2, zero));
1672 (void)apf.convertFromZeroExtendedInteger(&Val,
1673 MVT::getSizeInBits(Operand.getValueType()),
1674 Opcode==ISD::SINT_TO_FP,
1675 APFloat::rmNearestTiesToEven);
1676 return getConstantFP(apf, VT);
1678 case ISD::BIT_CONVERT:
1679 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
1680 return getConstantFP(BitsToFloat(Val), VT);
1681 else if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
1682 return getConstantFP(BitsToDouble(Val), VT);
1686 default: assert(0 && "Invalid bswap!"); break;
1687 case MVT::i16: return getConstant(ByteSwap_16((unsigned short)Val), VT);
1688 case MVT::i32: return getConstant(ByteSwap_32((unsigned)Val), VT);
1689 case MVT::i64: return getConstant(ByteSwap_64(Val), VT);
1694 default: assert(0 && "Invalid ctpop!"); break;
1695 case MVT::i1: return getConstant(Val != 0, VT);
1697 Tmp1 = (unsigned)Val & 0xFF;
1698 return getConstant(CountPopulation_32(Tmp1), VT);
1700 Tmp1 = (unsigned)Val & 0xFFFF;
1701 return getConstant(CountPopulation_32(Tmp1), VT);
1703 return getConstant(CountPopulation_32((unsigned)Val), VT);
1705 return getConstant(CountPopulation_64(Val), VT);
1709 default: assert(0 && "Invalid ctlz!"); break;
1710 case MVT::i1: return getConstant(Val == 0, VT);
1712 Tmp1 = (unsigned)Val & 0xFF;
1713 return getConstant(CountLeadingZeros_32(Tmp1)-24, VT);
1715 Tmp1 = (unsigned)Val & 0xFFFF;
1716 return getConstant(CountLeadingZeros_32(Tmp1)-16, VT);
1718 return getConstant(CountLeadingZeros_32((unsigned)Val), VT);
1720 return getConstant(CountLeadingZeros_64(Val), VT);
1724 default: assert(0 && "Invalid cttz!"); break;
1725 case MVT::i1: return getConstant(Val == 0, VT);
1727 Tmp1 = (unsigned)Val | 0x100;
1728 return getConstant(CountTrailingZeros_32(Tmp1), VT);
1730 Tmp1 = (unsigned)Val | 0x10000;
1731 return getConstant(CountTrailingZeros_32(Tmp1), VT);
1733 return getConstant(CountTrailingZeros_32((unsigned)Val), VT);
1735 return getConstant(CountTrailingZeros_64(Val), VT);
1740 // Constant fold unary operations with a floating point constant operand.
1741 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand.Val)) {
1742 APFloat V = C->getValueAPF(); // make copy
1743 if (VT != MVT::ppcf128 && Operand.getValueType() != MVT::ppcf128) {
1747 return getConstantFP(V, VT);
1750 return getConstantFP(V, VT);
1752 case ISD::FP_EXTEND:
1753 // This can return overflow, underflow, or inexact; we don't care.
1754 // FIXME need to be more flexible about rounding mode.
1755 (void) V.convert(VT==MVT::f32 ? APFloat::IEEEsingle :
1756 VT==MVT::f64 ? APFloat::IEEEdouble :
1757 VT==MVT::f80 ? APFloat::x87DoubleExtended :
1758 VT==MVT::f128 ? APFloat::IEEEquad :
1760 APFloat::rmNearestTiesToEven);
1761 return getConstantFP(V, VT);
1762 case ISD::FP_TO_SINT:
1763 case ISD::FP_TO_UINT: {
1765 assert(integerPartWidth >= 64);
1766 // FIXME need to be more flexible about rounding mode.
1767 APFloat::opStatus s = V.convertToInteger(&x, 64U,
1768 Opcode==ISD::FP_TO_SINT,
1769 APFloat::rmTowardZero);
1770 if (s==APFloat::opInvalidOp) // inexact is OK, in fact usual
1772 return getConstant(x, VT);
1774 case ISD::BIT_CONVERT:
1775 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
1776 return getConstant((uint32_t)V.convertToAPInt().getZExtValue(), VT);
1777 else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
1778 return getConstant(V.convertToAPInt().getZExtValue(), VT);
1784 unsigned OpOpcode = Operand.Val->getOpcode();
1786 case ISD::TokenFactor:
1787 return Operand; // Factor of one node? No factor.
1788 case ISD::FP_ROUND: assert(0 && "Invalid method to make FP_ROUND node");
1789 case ISD::FP_EXTEND:
1790 assert(MVT::isFloatingPoint(VT) &&
1791 MVT::isFloatingPoint(Operand.getValueType()) && "Invalid FP cast!");
1792 if (Operand.getValueType() == VT) return Operand; // noop conversion.
1794 case ISD::SIGN_EXTEND:
1795 assert(MVT::isInteger(VT) && MVT::isInteger(Operand.getValueType()) &&
1796 "Invalid SIGN_EXTEND!");
1797 if (Operand.getValueType() == VT) return Operand; // noop extension
1798 assert(MVT::getSizeInBits(Operand.getValueType()) < MVT::getSizeInBits(VT)
1799 && "Invalid sext node, dst < src!");
1800 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
1801 return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
1803 case ISD::ZERO_EXTEND:
1804 assert(MVT::isInteger(VT) && MVT::isInteger(Operand.getValueType()) &&
1805 "Invalid ZERO_EXTEND!");
1806 if (Operand.getValueType() == VT) return Operand; // noop extension
1807 assert(MVT::getSizeInBits(Operand.getValueType()) < MVT::getSizeInBits(VT)
1808 && "Invalid zext node, dst < src!");
1809 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x)
1810 return getNode(ISD::ZERO_EXTEND, VT, Operand.Val->getOperand(0));
1812 case ISD::ANY_EXTEND:
1813 assert(MVT::isInteger(VT) && MVT::isInteger(Operand.getValueType()) &&
1814 "Invalid ANY_EXTEND!");
1815 if (Operand.getValueType() == VT) return Operand; // noop extension
1816 assert(MVT::getSizeInBits(Operand.getValueType()) < MVT::getSizeInBits(VT)
1817 && "Invalid anyext node, dst < src!");
1818 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND)
1819 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x)
1820 return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
1823 assert(MVT::isInteger(VT) && MVT::isInteger(Operand.getValueType()) &&
1824 "Invalid TRUNCATE!");
1825 if (Operand.getValueType() == VT) return Operand; // noop truncate
1826 assert(MVT::getSizeInBits(Operand.getValueType()) > MVT::getSizeInBits(VT)
1827 && "Invalid truncate node, src < dst!");
1828 if (OpOpcode == ISD::TRUNCATE)
1829 return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
1830 else if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
1831 OpOpcode == ISD::ANY_EXTEND) {
1832 // If the source is smaller than the dest, we still need an extend.
1833 if (MVT::getSizeInBits(Operand.Val->getOperand(0).getValueType())
1834 < MVT::getSizeInBits(VT))
1835 return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
1836 else if (MVT::getSizeInBits(Operand.Val->getOperand(0).getValueType())
1837 > MVT::getSizeInBits(VT))
1838 return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
1840 return Operand.Val->getOperand(0);
1843 case ISD::BIT_CONVERT:
1844 // Basic sanity checking.
1845 assert(MVT::getSizeInBits(VT) == MVT::getSizeInBits(Operand.getValueType())
1846 && "Cannot BIT_CONVERT between types of different sizes!");
1847 if (VT == Operand.getValueType()) return Operand; // noop conversion.
1848 if (OpOpcode == ISD::BIT_CONVERT) // bitconv(bitconv(x)) -> bitconv(x)
1849 return getNode(ISD::BIT_CONVERT, VT, Operand.getOperand(0));
1850 if (OpOpcode == ISD::UNDEF)
1851 return getNode(ISD::UNDEF, VT);
1853 case ISD::SCALAR_TO_VECTOR:
1854 assert(MVT::isVector(VT) && !MVT::isVector(Operand.getValueType()) &&
1855 MVT::getVectorElementType(VT) == Operand.getValueType() &&
1856 "Illegal SCALAR_TO_VECTOR node!");
1859 if (OpOpcode == ISD::FSUB) // -(X-Y) -> (Y-X)
1860 return getNode(ISD::FSUB, VT, Operand.Val->getOperand(1),
1861 Operand.Val->getOperand(0));
1862 if (OpOpcode == ISD::FNEG) // --X -> X
1863 return Operand.Val->getOperand(0);
1866 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X)
1867 return getNode(ISD::FABS, VT, Operand.Val->getOperand(0));
1872 SDVTList VTs = getVTList(VT);
1873 if (VT != MVT::Flag) { // Don't CSE flag producing nodes
1874 FoldingSetNodeID ID;
1875 SDOperand Ops[1] = { Operand };
1876 AddNodeIDNode(ID, Opcode, VTs, Ops, 1);
1878 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1879 return SDOperand(E, 0);
1880 N = new UnarySDNode(Opcode, VTs, Operand);
1881 CSEMap.InsertNode(N, IP);
1883 N = new UnarySDNode(Opcode, VTs, Operand);
1885 AllNodes.push_back(N);
1886 return SDOperand(N, 0);
1891 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
1892 SDOperand N1, SDOperand N2) {
1893 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
1894 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
1897 case ISD::TokenFactor:
1898 assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
1899 N2.getValueType() == MVT::Other && "Invalid token factor!");
1900 // Fold trivial token factors.
1901 if (N1.getOpcode() == ISD::EntryToken) return N2;
1902 if (N2.getOpcode() == ISD::EntryToken) return N1;
1905 assert(MVT::isInteger(VT) && N1.getValueType() == N2.getValueType() &&
1906 N1.getValueType() == VT && "Binary operator types must match!");
1907 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's
1908 // worth handling here.
1909 if (N2C && N2C->getValue() == 0)
1911 if (N2C && N2C->isAllOnesValue()) // X & -1 -> X
1916 assert(MVT::isInteger(VT) && N1.getValueType() == N2.getValueType() &&
1917 N1.getValueType() == VT && "Binary operator types must match!");
1918 // (X ^| 0) -> X. This commonly occurs when legalizing i64 values, so it's
1919 // worth handling here.
1920 if (N2C && N2C->getValue() == 0)
1927 assert(MVT::isInteger(VT) && "This operator does not apply to FP types!");
1939 assert(N1.getValueType() == N2.getValueType() &&
1940 N1.getValueType() == VT && "Binary operator types must match!");
1942 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match.
1943 assert(N1.getValueType() == VT &&
1944 MVT::isFloatingPoint(N1.getValueType()) &&
1945 MVT::isFloatingPoint(N2.getValueType()) &&
1946 "Invalid FCOPYSIGN!");
1953 assert(VT == N1.getValueType() &&
1954 "Shift operators return type must be the same as their first arg");
1955 assert(MVT::isInteger(VT) && MVT::isInteger(N2.getValueType()) &&
1956 VT != MVT::i1 && "Shifts only work on integers");
1958 case ISD::FP_ROUND_INREG: {
1959 MVT::ValueType EVT = cast<VTSDNode>(N2)->getVT();
1960 assert(VT == N1.getValueType() && "Not an inreg round!");
1961 assert(MVT::isFloatingPoint(VT) && MVT::isFloatingPoint(EVT) &&
1962 "Cannot FP_ROUND_INREG integer types");
1963 assert(MVT::getSizeInBits(EVT) <= MVT::getSizeInBits(VT) &&
1964 "Not rounding down!");
1965 if (cast<VTSDNode>(N2)->getVT() == VT) return N1; // Not actually rounding.
1969 assert(MVT::isFloatingPoint(VT) &&
1970 MVT::isFloatingPoint(N1.getValueType()) &&
1971 MVT::getSizeInBits(VT) <= MVT::getSizeInBits(N1.getValueType()) &&
1972 isa<ConstantSDNode>(N2) && "Invalid FP_ROUND!");
1973 if (N1.getValueType() == VT) return N1; // noop conversion.
1975 case ISD::AssertSext:
1976 case ISD::AssertZext: {
1977 MVT::ValueType EVT = cast<VTSDNode>(N2)->getVT();
1978 assert(VT == N1.getValueType() && "Not an inreg extend!");
1979 assert(MVT::isInteger(VT) && MVT::isInteger(EVT) &&
1980 "Cannot *_EXTEND_INREG FP types");
1981 assert(MVT::getSizeInBits(EVT) <= MVT::getSizeInBits(VT) &&
1985 case ISD::SIGN_EXTEND_INREG: {
1986 MVT::ValueType EVT = cast<VTSDNode>(N2)->getVT();
1987 assert(VT == N1.getValueType() && "Not an inreg extend!");
1988 assert(MVT::isInteger(VT) && MVT::isInteger(EVT) &&
1989 "Cannot *_EXTEND_INREG FP types");
1990 assert(MVT::getSizeInBits(EVT) <= MVT::getSizeInBits(VT) &&
1992 if (EVT == VT) return N1; // Not actually extending
1995 int64_t Val = N1C->getValue();
1996 unsigned FromBits = MVT::getSizeInBits(cast<VTSDNode>(N2)->getVT());
1997 Val <<= 64-FromBits;
1998 Val >>= 64-FromBits;
1999 return getConstant(Val, VT);
2003 case ISD::EXTRACT_VECTOR_ELT:
2004 assert(N2C && "Bad EXTRACT_VECTOR_ELT!");
2006 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
2007 // expanding copies of large vectors from registers.
2008 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
2009 N1.getNumOperands() > 0) {
2011 MVT::getVectorNumElements(N1.getOperand(0).getValueType());
2012 return getNode(ISD::EXTRACT_VECTOR_ELT, VT,
2013 N1.getOperand(N2C->getValue() / Factor),
2014 getConstant(N2C->getValue() % Factor, N2.getValueType()));
2017 // EXTRACT_VECTOR_ELT of BUILD_VECTOR is often formed while lowering is
2018 // expanding large vector constants.
2019 if (N1.getOpcode() == ISD::BUILD_VECTOR)
2020 return N1.getOperand(N2C->getValue());
2022 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
2023 // operations are lowered to scalars.
2024 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT)
2025 if (ConstantSDNode *IEC = dyn_cast<ConstantSDNode>(N1.getOperand(2))) {
2027 return N1.getOperand(1);
2029 return getNode(ISD::EXTRACT_VECTOR_ELT, VT, N1.getOperand(0), N2);
2032 case ISD::EXTRACT_ELEMENT:
2033 assert(N2C && (unsigned)N2C->getValue() < 2 && "Bad EXTRACT_ELEMENT!");
2035 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
2036 // 64-bit integers into 32-bit parts. Instead of building the extract of
2037 // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
2038 if (N1.getOpcode() == ISD::BUILD_PAIR)
2039 return N1.getOperand(N2C->getValue());
2041 // EXTRACT_ELEMENT of a constant int is also very common.
2042 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2043 unsigned Shift = MVT::getSizeInBits(VT) * N2C->getValue();
2044 return getConstant(C->getValue() >> Shift, VT);
2051 uint64_t C1 = N1C->getValue(), C2 = N2C->getValue();
2053 case ISD::ADD: return getConstant(C1 + C2, VT);
2054 case ISD::SUB: return getConstant(C1 - C2, VT);
2055 case ISD::MUL: return getConstant(C1 * C2, VT);
2057 if (C2) return getConstant(C1 / C2, VT);
2060 if (C2) return getConstant(C1 % C2, VT);
2063 if (C2) return getConstant(N1C->getSignExtended() /
2064 N2C->getSignExtended(), VT);
2067 if (C2) return getConstant(N1C->getSignExtended() %
2068 N2C->getSignExtended(), VT);
2070 case ISD::AND : return getConstant(C1 & C2, VT);
2071 case ISD::OR : return getConstant(C1 | C2, VT);
2072 case ISD::XOR : return getConstant(C1 ^ C2, VT);
2073 case ISD::SHL : return getConstant(C1 << C2, VT);
2074 case ISD::SRL : return getConstant(C1 >> C2, VT);
2075 case ISD::SRA : return getConstant(N1C->getSignExtended() >>(int)C2, VT);
2077 return getConstant((C1 << C2) | (C1 >> (MVT::getSizeInBits(VT) - C2)),
2080 return getConstant((C1 >> C2) | (C1 << (MVT::getSizeInBits(VT) - C2)),
2084 } else { // Cannonicalize constant to RHS if commutative
2085 if (isCommutativeBinOp(Opcode)) {
2086 std::swap(N1C, N2C);
2092 // Constant fold FP operations.
2093 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1.Val);
2094 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2.Val);
2096 if (!N2CFP && isCommutativeBinOp(Opcode)) {
2097 // Cannonicalize constant to RHS if commutative
2098 std::swap(N1CFP, N2CFP);
2100 } else if (N2CFP && VT != MVT::ppcf128) {
2101 APFloat V1 = N1CFP->getValueAPF(), V2 = N2CFP->getValueAPF();
2102 APFloat::opStatus s;
2105 s = V1.add(V2, APFloat::rmNearestTiesToEven);
2106 if (s != APFloat::opInvalidOp)
2107 return getConstantFP(V1, VT);
2110 s = V1.subtract(V2, APFloat::rmNearestTiesToEven);
2111 if (s!=APFloat::opInvalidOp)
2112 return getConstantFP(V1, VT);
2115 s = V1.multiply(V2, APFloat::rmNearestTiesToEven);
2116 if (s!=APFloat::opInvalidOp)
2117 return getConstantFP(V1, VT);
2120 s = V1.divide(V2, APFloat::rmNearestTiesToEven);
2121 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2122 return getConstantFP(V1, VT);
2125 s = V1.mod(V2, APFloat::rmNearestTiesToEven);
2126 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2127 return getConstantFP(V1, VT);
2129 case ISD::FCOPYSIGN:
2131 return getConstantFP(V1, VT);
2137 // Canonicalize an UNDEF to the RHS, even over a constant.
2138 if (N1.getOpcode() == ISD::UNDEF) {
2139 if (isCommutativeBinOp(Opcode)) {
2143 case ISD::FP_ROUND_INREG:
2144 case ISD::SIGN_EXTEND_INREG:
2150 return N1; // fold op(undef, arg2) -> undef
2157 if (!MVT::isVector(VT))
2158 return getConstant(0, VT); // fold op(undef, arg2) -> 0
2159 // For vectors, we can't easily build an all zero vector, just return
2166 // Fold a bunch of operators when the RHS is undef.
2167 if (N2.getOpcode() == ISD::UNDEF) {
2183 return N2; // fold op(arg1, undef) -> undef
2188 if (!MVT::isVector(VT))
2189 return getConstant(0, VT); // fold op(arg1, undef) -> 0
2190 // For vectors, we can't easily build an all zero vector, just return
2194 if (!MVT::isVector(VT))
2195 return getConstant(MVT::getIntVTBitMask(VT), VT);
2196 // For vectors, we can't easily build an all one vector, just return
2204 // Memoize this node if possible.
2206 SDVTList VTs = getVTList(VT);
2207 if (VT != MVT::Flag) {
2208 SDOperand Ops[] = { N1, N2 };
2209 FoldingSetNodeID ID;
2210 AddNodeIDNode(ID, Opcode, VTs, Ops, 2);
2212 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2213 return SDOperand(E, 0);
2214 N = new BinarySDNode(Opcode, VTs, N1, N2);
2215 CSEMap.InsertNode(N, IP);
2217 N = new BinarySDNode(Opcode, VTs, N1, N2);
2220 AllNodes.push_back(N);
2221 return SDOperand(N, 0);
2224 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
2225 SDOperand N1, SDOperand N2, SDOperand N3) {
2226 // Perform various simplifications.
2227 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
2228 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
2231 // Use FoldSetCC to simplify SETCC's.
2232 SDOperand Simp = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get());
2233 if (Simp.Val) return Simp;
2238 if (N1C->getValue())
2239 return N2; // select true, X, Y -> X
2241 return N3; // select false, X, Y -> Y
2243 if (N2 == N3) return N2; // select C, X, X -> X
2247 if (N2C->getValue()) // Unconditional branch
2248 return getNode(ISD::BR, MVT::Other, N1, N3);
2250 return N1; // Never-taken branch
2252 case ISD::VECTOR_SHUFFLE:
2253 assert(VT == N1.getValueType() && VT == N2.getValueType() &&
2254 MVT::isVector(VT) && MVT::isVector(N3.getValueType()) &&
2255 N3.getOpcode() == ISD::BUILD_VECTOR &&
2256 MVT::getVectorNumElements(VT) == N3.getNumOperands() &&
2257 "Illegal VECTOR_SHUFFLE node!");
2259 case ISD::BIT_CONVERT:
2260 // Fold bit_convert nodes from a type to themselves.
2261 if (N1.getValueType() == VT)
2266 // Memoize node if it doesn't produce a flag.
2268 SDVTList VTs = getVTList(VT);
2269 if (VT != MVT::Flag) {
2270 SDOperand Ops[] = { N1, N2, N3 };
2271 FoldingSetNodeID ID;
2272 AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
2274 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2275 return SDOperand(E, 0);
2276 N = new TernarySDNode(Opcode, VTs, N1, N2, N3);
2277 CSEMap.InsertNode(N, IP);
2279 N = new TernarySDNode(Opcode, VTs, N1, N2, N3);
2281 AllNodes.push_back(N);
2282 return SDOperand(N, 0);
2285 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
2286 SDOperand N1, SDOperand N2, SDOperand N3,
2288 SDOperand Ops[] = { N1, N2, N3, N4 };
2289 return getNode(Opcode, VT, Ops, 4);
2292 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
2293 SDOperand N1, SDOperand N2, SDOperand N3,
2294 SDOperand N4, SDOperand N5) {
2295 SDOperand Ops[] = { N1, N2, N3, N4, N5 };
2296 return getNode(Opcode, VT, Ops, 5);
2299 SDOperand SelectionDAG::getMemcpy(SDOperand Chain, SDOperand Dest,
2300 SDOperand Src, SDOperand Size,
2302 SDOperand AlwaysInline) {
2303 SDOperand Ops[] = { Chain, Dest, Src, Size, Align, AlwaysInline };
2304 return getNode(ISD::MEMCPY, MVT::Other, Ops, 6);
2307 SDOperand SelectionDAG::getMemmove(SDOperand Chain, SDOperand Dest,
2308 SDOperand Src, SDOperand Size,
2310 SDOperand AlwaysInline) {
2311 SDOperand Ops[] = { Chain, Dest, Src, Size, Align, AlwaysInline };
2312 return getNode(ISD::MEMMOVE, MVT::Other, Ops, 6);
2315 SDOperand SelectionDAG::getMemset(SDOperand Chain, SDOperand Dest,
2316 SDOperand Src, SDOperand Size,
2318 SDOperand AlwaysInline) {
2319 SDOperand Ops[] = { Chain, Dest, Src, Size, Align, AlwaysInline };
2320 return getNode(ISD::MEMSET, MVT::Other, Ops, 6);
2323 SDOperand SelectionDAG::getLoad(MVT::ValueType VT,
2324 SDOperand Chain, SDOperand Ptr,
2325 const Value *SV, int SVOffset,
2326 bool isVolatile, unsigned Alignment) {
2327 if (Alignment == 0) { // Ensure that codegen never sees alignment 0
2329 if (VT != MVT::iPTR) {
2330 Ty = MVT::getTypeForValueType(VT);
2332 const PointerType *PT = dyn_cast<PointerType>(SV->getType());
2333 assert(PT && "Value for load must be a pointer");
2334 Ty = PT->getElementType();
2336 assert(Ty && "Could not get type information for load");
2337 Alignment = TLI.getTargetData()->getABITypeAlignment(Ty);
2339 SDVTList VTs = getVTList(VT, MVT::Other);
2340 SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
2341 SDOperand Ops[] = { Chain, Ptr, Undef };
2342 FoldingSetNodeID ID;
2343 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops, 3);
2344 ID.AddInteger(ISD::UNINDEXED);
2345 ID.AddInteger(ISD::NON_EXTLOAD);
2346 ID.AddInteger((unsigned int)VT);
2347 ID.AddInteger(Alignment);
2348 ID.AddInteger(isVolatile);
2350 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2351 return SDOperand(E, 0);
2352 SDNode *N = new LoadSDNode(Ops, VTs, ISD::UNINDEXED,
2353 ISD::NON_EXTLOAD, VT, SV, SVOffset, Alignment,
2355 CSEMap.InsertNode(N, IP);
2356 AllNodes.push_back(N);
2357 return SDOperand(N, 0);
2360 SDOperand SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, MVT::ValueType VT,
2361 SDOperand Chain, SDOperand Ptr,
2363 int SVOffset, MVT::ValueType EVT,
2364 bool isVolatile, unsigned Alignment) {
2365 // If they are asking for an extending load from/to the same thing, return a
2368 return getLoad(VT, Chain, Ptr, SV, SVOffset, isVolatile, Alignment);
2370 if (MVT::isVector(VT))
2371 assert(EVT == MVT::getVectorElementType(VT) && "Invalid vector extload!");
2373 assert(MVT::getSizeInBits(EVT) < MVT::getSizeInBits(VT) &&
2374 "Should only be an extending load, not truncating!");
2375 assert((ExtType == ISD::EXTLOAD || MVT::isInteger(VT)) &&
2376 "Cannot sign/zero extend a FP/Vector load!");
2377 assert(MVT::isInteger(VT) == MVT::isInteger(EVT) &&
2378 "Cannot convert from FP to Int or Int -> FP!");
2380 if (Alignment == 0) { // Ensure that codegen never sees alignment 0
2382 if (VT != MVT::iPTR) {
2383 Ty = MVT::getTypeForValueType(VT);
2385 const PointerType *PT = dyn_cast<PointerType>(SV->getType());
2386 assert(PT && "Value for load must be a pointer");
2387 Ty = PT->getElementType();
2389 assert(Ty && "Could not get type information for load");
2390 Alignment = TLI.getTargetData()->getABITypeAlignment(Ty);
2392 SDVTList VTs = getVTList(VT, MVT::Other);
2393 SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
2394 SDOperand Ops[] = { Chain, Ptr, Undef };
2395 FoldingSetNodeID ID;
2396 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops, 3);
2397 ID.AddInteger(ISD::UNINDEXED);
2398 ID.AddInteger(ExtType);
2399 ID.AddInteger((unsigned int)EVT);
2400 ID.AddInteger(Alignment);
2401 ID.AddInteger(isVolatile);
2403 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2404 return SDOperand(E, 0);
2405 SDNode *N = new LoadSDNode(Ops, VTs, ISD::UNINDEXED, ExtType, EVT,
2406 SV, SVOffset, Alignment, isVolatile);
2407 CSEMap.InsertNode(N, IP);
2408 AllNodes.push_back(N);
2409 return SDOperand(N, 0);
2413 SelectionDAG::getIndexedLoad(SDOperand OrigLoad, SDOperand Base,
2414 SDOperand Offset, ISD::MemIndexedMode AM) {
2415 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
2416 assert(LD->getOffset().getOpcode() == ISD::UNDEF &&
2417 "Load is already a indexed load!");
2418 MVT::ValueType VT = OrigLoad.getValueType();
2419 SDVTList VTs = getVTList(VT, Base.getValueType(), MVT::Other);
2420 SDOperand Ops[] = { LD->getChain(), Base, Offset };
2421 FoldingSetNodeID ID;
2422 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops, 3);
2424 ID.AddInteger(LD->getExtensionType());
2425 ID.AddInteger((unsigned int)(LD->getMemoryVT()));
2426 ID.AddInteger(LD->getAlignment());
2427 ID.AddInteger(LD->isVolatile());
2429 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2430 return SDOperand(E, 0);
2431 SDNode *N = new LoadSDNode(Ops, VTs, AM,
2432 LD->getExtensionType(), LD->getMemoryVT(),
2433 LD->getSrcValue(), LD->getSrcValueOffset(),
2434 LD->getAlignment(), LD->isVolatile());
2435 CSEMap.InsertNode(N, IP);
2436 AllNodes.push_back(N);
2437 return SDOperand(N, 0);
2440 SDOperand SelectionDAG::getStore(SDOperand Chain, SDOperand Val,
2441 SDOperand Ptr, const Value *SV, int SVOffset,
2442 bool isVolatile, unsigned Alignment) {
2443 MVT::ValueType VT = Val.getValueType();
2445 if (Alignment == 0) { // Ensure that codegen never sees alignment 0
2447 if (VT != MVT::iPTR) {
2448 Ty = MVT::getTypeForValueType(VT);
2450 const PointerType *PT = dyn_cast<PointerType>(SV->getType());
2451 assert(PT && "Value for store must be a pointer");
2452 Ty = PT->getElementType();
2454 assert(Ty && "Could not get type information for store");
2455 Alignment = TLI.getTargetData()->getABITypeAlignment(Ty);
2457 SDVTList VTs = getVTList(MVT::Other);
2458 SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
2459 SDOperand Ops[] = { Chain, Val, Ptr, Undef };
2460 FoldingSetNodeID ID;
2461 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
2462 ID.AddInteger(ISD::UNINDEXED);
2463 ID.AddInteger(false);
2464 ID.AddInteger((unsigned int)VT);
2465 ID.AddInteger(Alignment);
2466 ID.AddInteger(isVolatile);
2468 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2469 return SDOperand(E, 0);
2470 SDNode *N = new StoreSDNode(Ops, VTs, ISD::UNINDEXED, false,
2471 VT, SV, SVOffset, Alignment, isVolatile);
2472 CSEMap.InsertNode(N, IP);
2473 AllNodes.push_back(N);
2474 return SDOperand(N, 0);
2477 SDOperand SelectionDAG::getTruncStore(SDOperand Chain, SDOperand Val,
2478 SDOperand Ptr, const Value *SV,
2479 int SVOffset, MVT::ValueType SVT,
2480 bool isVolatile, unsigned Alignment) {
2481 MVT::ValueType VT = Val.getValueType();
2484 return getStore(Chain, Val, Ptr, SV, SVOffset, isVolatile, Alignment);
2486 assert(MVT::getSizeInBits(VT) > MVT::getSizeInBits(SVT) &&
2487 "Not a truncation?");
2488 assert(MVT::isInteger(VT) == MVT::isInteger(SVT) &&
2489 "Can't do FP-INT conversion!");
2491 if (Alignment == 0) { // Ensure that codegen never sees alignment 0
2493 if (VT != MVT::iPTR) {
2494 Ty = MVT::getTypeForValueType(VT);
2496 const PointerType *PT = dyn_cast<PointerType>(SV->getType());
2497 assert(PT && "Value for store must be a pointer");
2498 Ty = PT->getElementType();
2500 assert(Ty && "Could not get type information for store");
2501 Alignment = TLI.getTargetData()->getABITypeAlignment(Ty);
2503 SDVTList VTs = getVTList(MVT::Other);
2504 SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
2505 SDOperand Ops[] = { Chain, Val, Ptr, Undef };
2506 FoldingSetNodeID ID;
2507 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
2508 ID.AddInteger(ISD::UNINDEXED);
2510 ID.AddInteger((unsigned int)SVT);
2511 ID.AddInteger(Alignment);
2512 ID.AddInteger(isVolatile);
2514 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2515 return SDOperand(E, 0);
2516 SDNode *N = new StoreSDNode(Ops, VTs, ISD::UNINDEXED, true,
2517 SVT, SV, SVOffset, Alignment, isVolatile);
2518 CSEMap.InsertNode(N, IP);
2519 AllNodes.push_back(N);
2520 return SDOperand(N, 0);
2524 SelectionDAG::getIndexedStore(SDOperand OrigStore, SDOperand Base,
2525 SDOperand Offset, ISD::MemIndexedMode AM) {
2526 StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
2527 assert(ST->getOffset().getOpcode() == ISD::UNDEF &&
2528 "Store is already a indexed store!");
2529 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
2530 SDOperand Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
2531 FoldingSetNodeID ID;
2532 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
2534 ID.AddInteger(ST->isTruncatingStore());
2535 ID.AddInteger((unsigned int)(ST->getMemoryVT()));
2536 ID.AddInteger(ST->getAlignment());
2537 ID.AddInteger(ST->isVolatile());
2539 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2540 return SDOperand(E, 0);
2541 SDNode *N = new StoreSDNode(Ops, VTs, AM,
2542 ST->isTruncatingStore(), ST->getMemoryVT(),
2543 ST->getSrcValue(), ST->getSrcValueOffset(),
2544 ST->getAlignment(), ST->isVolatile());
2545 CSEMap.InsertNode(N, IP);
2546 AllNodes.push_back(N);
2547 return SDOperand(N, 0);
2550 SDOperand SelectionDAG::getVAArg(MVT::ValueType VT,
2551 SDOperand Chain, SDOperand Ptr,
2553 SDOperand Ops[] = { Chain, Ptr, SV };
2554 return getNode(ISD::VAARG, getVTList(VT, MVT::Other), Ops, 3);
2557 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
2558 const SDOperand *Ops, unsigned NumOps) {
2560 case 0: return getNode(Opcode, VT);
2561 case 1: return getNode(Opcode, VT, Ops[0]);
2562 case 2: return getNode(Opcode, VT, Ops[0], Ops[1]);
2563 case 3: return getNode(Opcode, VT, Ops[0], Ops[1], Ops[2]);
2569 case ISD::SELECT_CC: {
2570 assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
2571 assert(Ops[0].getValueType() == Ops[1].getValueType() &&
2572 "LHS and RHS of condition must have same type!");
2573 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
2574 "True and False arms of SelectCC must have same type!");
2575 assert(Ops[2].getValueType() == VT &&
2576 "select_cc node must be of same type as true and false value!");
2580 assert(NumOps == 5 && "BR_CC takes 5 operands!");
2581 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
2582 "LHS/RHS of comparison should match types!");
2589 SDVTList VTs = getVTList(VT);
2590 if (VT != MVT::Flag) {
2591 FoldingSetNodeID ID;
2592 AddNodeIDNode(ID, Opcode, VTs, Ops, NumOps);
2594 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2595 return SDOperand(E, 0);
2596 N = new SDNode(Opcode, VTs, Ops, NumOps);
2597 CSEMap.InsertNode(N, IP);
2599 N = new SDNode(Opcode, VTs, Ops, NumOps);
2601 AllNodes.push_back(N);
2602 return SDOperand(N, 0);
2605 SDOperand SelectionDAG::getNode(unsigned Opcode,
2606 std::vector<MVT::ValueType> &ResultTys,
2607 const SDOperand *Ops, unsigned NumOps) {
2608 return getNode(Opcode, getNodeValueTypes(ResultTys), ResultTys.size(),
2612 SDOperand SelectionDAG::getNode(unsigned Opcode,
2613 const MVT::ValueType *VTs, unsigned NumVTs,
2614 const SDOperand *Ops, unsigned NumOps) {
2616 return getNode(Opcode, VTs[0], Ops, NumOps);
2617 return getNode(Opcode, makeVTList(VTs, NumVTs), Ops, NumOps);
2620 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
2621 const SDOperand *Ops, unsigned NumOps) {
2622 if (VTList.NumVTs == 1)
2623 return getNode(Opcode, VTList.VTs[0], Ops, NumOps);
2626 // FIXME: figure out how to safely handle things like
2627 // int foo(int x) { return 1 << (x & 255); }
2628 // int bar() { return foo(256); }
2630 case ISD::SRA_PARTS:
2631 case ISD::SRL_PARTS:
2632 case ISD::SHL_PARTS:
2633 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
2634 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
2635 return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
2636 else if (N3.getOpcode() == ISD::AND)
2637 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
2638 // If the and is only masking out bits that cannot effect the shift,
2639 // eliminate the and.
2640 unsigned NumBits = MVT::getSizeInBits(VT)*2;
2641 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
2642 return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
2648 // Memoize the node unless it returns a flag.
2650 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
2651 FoldingSetNodeID ID;
2652 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
2654 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2655 return SDOperand(E, 0);
2657 N = new UnarySDNode(Opcode, VTList, Ops[0]);
2658 else if (NumOps == 2)
2659 N = new BinarySDNode(Opcode, VTList, Ops[0], Ops[1]);
2660 else if (NumOps == 3)
2661 N = new TernarySDNode(Opcode, VTList, Ops[0], Ops[1], Ops[2]);
2663 N = new SDNode(Opcode, VTList, Ops, NumOps);
2664 CSEMap.InsertNode(N, IP);
2667 N = new UnarySDNode(Opcode, VTList, Ops[0]);
2668 else if (NumOps == 2)
2669 N = new BinarySDNode(Opcode, VTList, Ops[0], Ops[1]);
2670 else if (NumOps == 3)
2671 N = new TernarySDNode(Opcode, VTList, Ops[0], Ops[1], Ops[2]);
2673 N = new SDNode(Opcode, VTList, Ops, NumOps);
2675 AllNodes.push_back(N);
2676 return SDOperand(N, 0);
2679 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList) {
2680 return getNode(Opcode, VTList, 0, 0);
2683 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
2685 SDOperand Ops[] = { N1 };
2686 return getNode(Opcode, VTList, Ops, 1);
2689 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
2690 SDOperand N1, SDOperand N2) {
2691 SDOperand Ops[] = { N1, N2 };
2692 return getNode(Opcode, VTList, Ops, 2);
2695 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
2696 SDOperand N1, SDOperand N2, SDOperand N3) {
2697 SDOperand Ops[] = { N1, N2, N3 };
2698 return getNode(Opcode, VTList, Ops, 3);
2701 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
2702 SDOperand N1, SDOperand N2, SDOperand N3,
2704 SDOperand Ops[] = { N1, N2, N3, N4 };
2705 return getNode(Opcode, VTList, Ops, 4);
2708 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
2709 SDOperand N1, SDOperand N2, SDOperand N3,
2710 SDOperand N4, SDOperand N5) {
2711 SDOperand Ops[] = { N1, N2, N3, N4, N5 };
2712 return getNode(Opcode, VTList, Ops, 5);
2715 SDVTList SelectionDAG::getVTList(MVT::ValueType VT) {
2716 return makeVTList(SDNode::getValueTypeList(VT), 1);
2719 SDVTList SelectionDAG::getVTList(MVT::ValueType VT1, MVT::ValueType VT2) {
2720 for (std::list<std::vector<MVT::ValueType> >::iterator I = VTList.begin(),
2721 E = VTList.end(); I != E; ++I) {
2722 if (I->size() == 2 && (*I)[0] == VT1 && (*I)[1] == VT2)
2723 return makeVTList(&(*I)[0], 2);
2725 std::vector<MVT::ValueType> V;
2728 VTList.push_front(V);
2729 return makeVTList(&(*VTList.begin())[0], 2);
2731 SDVTList SelectionDAG::getVTList(MVT::ValueType VT1, MVT::ValueType VT2,
2732 MVT::ValueType VT3) {
2733 for (std::list<std::vector<MVT::ValueType> >::iterator I = VTList.begin(),
2734 E = VTList.end(); I != E; ++I) {
2735 if (I->size() == 3 && (*I)[0] == VT1 && (*I)[1] == VT2 &&
2737 return makeVTList(&(*I)[0], 3);
2739 std::vector<MVT::ValueType> V;
2743 VTList.push_front(V);
2744 return makeVTList(&(*VTList.begin())[0], 3);
2747 SDVTList SelectionDAG::getVTList(const MVT::ValueType *VTs, unsigned NumVTs) {
2749 case 0: assert(0 && "Cannot have nodes without results!");
2750 case 1: return getVTList(VTs[0]);
2751 case 2: return getVTList(VTs[0], VTs[1]);
2752 case 3: return getVTList(VTs[0], VTs[1], VTs[2]);
2756 for (std::list<std::vector<MVT::ValueType> >::iterator I = VTList.begin(),
2757 E = VTList.end(); I != E; ++I) {
2758 if (I->size() != NumVTs || VTs[0] != (*I)[0] || VTs[1] != (*I)[1]) continue;
2760 bool NoMatch = false;
2761 for (unsigned i = 2; i != NumVTs; ++i)
2762 if (VTs[i] != (*I)[i]) {
2767 return makeVTList(&*I->begin(), NumVTs);
2770 VTList.push_front(std::vector<MVT::ValueType>(VTs, VTs+NumVTs));
2771 return makeVTList(&*VTList.begin()->begin(), NumVTs);
2775 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
2776 /// specified operands. If the resultant node already exists in the DAG,
2777 /// this does not modify the specified node, instead it returns the node that
2778 /// already exists. If the resultant node does not exist in the DAG, the
2779 /// input node is returned. As a degenerate case, if you specify the same
2780 /// input operands as the node already has, the input node is returned.
2781 SDOperand SelectionDAG::
2782 UpdateNodeOperands(SDOperand InN, SDOperand Op) {
2783 SDNode *N = InN.Val;
2784 assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
2786 // Check to see if there is no change.
2787 if (Op == N->getOperand(0)) return InN;
2789 // See if the modified node already exists.
2790 void *InsertPos = 0;
2791 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
2792 return SDOperand(Existing, InN.ResNo);
2794 // Nope it doesn't. Remove the node from it's current place in the maps.
2796 RemoveNodeFromCSEMaps(N);
2798 // Now we update the operands.
2799 N->OperandList[0].Val->removeUser(N);
2801 N->OperandList[0] = Op;
2803 // If this gets put into a CSE map, add it.
2804 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
2808 SDOperand SelectionDAG::
2809 UpdateNodeOperands(SDOperand InN, SDOperand Op1, SDOperand Op2) {
2810 SDNode *N = InN.Val;
2811 assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
2813 // Check to see if there is no change.
2814 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
2815 return InN; // No operands changed, just return the input node.
2817 // See if the modified node already exists.
2818 void *InsertPos = 0;
2819 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
2820 return SDOperand(Existing, InN.ResNo);
2822 // Nope it doesn't. Remove the node from it's current place in the maps.
2824 RemoveNodeFromCSEMaps(N);
2826 // Now we update the operands.
2827 if (N->OperandList[0] != Op1) {
2828 N->OperandList[0].Val->removeUser(N);
2829 Op1.Val->addUser(N);
2830 N->OperandList[0] = Op1;
2832 if (N->OperandList[1] != Op2) {
2833 N->OperandList[1].Val->removeUser(N);
2834 Op2.Val->addUser(N);
2835 N->OperandList[1] = Op2;
2838 // If this gets put into a CSE map, add it.
2839 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
2843 SDOperand SelectionDAG::
2844 UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2, SDOperand Op3) {
2845 SDOperand Ops[] = { Op1, Op2, Op3 };
2846 return UpdateNodeOperands(N, Ops, 3);
2849 SDOperand SelectionDAG::
2850 UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2,
2851 SDOperand Op3, SDOperand Op4) {
2852 SDOperand Ops[] = { Op1, Op2, Op3, Op4 };
2853 return UpdateNodeOperands(N, Ops, 4);
2856 SDOperand SelectionDAG::
2857 UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2,
2858 SDOperand Op3, SDOperand Op4, SDOperand Op5) {
2859 SDOperand Ops[] = { Op1, Op2, Op3, Op4, Op5 };
2860 return UpdateNodeOperands(N, Ops, 5);
2864 SDOperand SelectionDAG::
2865 UpdateNodeOperands(SDOperand InN, SDOperand *Ops, unsigned NumOps) {
2866 SDNode *N = InN.Val;
2867 assert(N->getNumOperands() == NumOps &&
2868 "Update with wrong number of operands");
2870 // Check to see if there is no change.
2871 bool AnyChange = false;
2872 for (unsigned i = 0; i != NumOps; ++i) {
2873 if (Ops[i] != N->getOperand(i)) {
2879 // No operands changed, just return the input node.
2880 if (!AnyChange) return InN;
2882 // See if the modified node already exists.
2883 void *InsertPos = 0;
2884 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, NumOps, InsertPos))
2885 return SDOperand(Existing, InN.ResNo);
2887 // Nope it doesn't. Remove the node from it's current place in the maps.
2889 RemoveNodeFromCSEMaps(N);
2891 // Now we update the operands.
2892 for (unsigned i = 0; i != NumOps; ++i) {
2893 if (N->OperandList[i] != Ops[i]) {
2894 N->OperandList[i].Val->removeUser(N);
2895 Ops[i].Val->addUser(N);
2896 N->OperandList[i] = Ops[i];
2900 // If this gets put into a CSE map, add it.
2901 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
2906 /// MorphNodeTo - This frees the operands of the current node, resets the
2907 /// opcode, types, and operands to the specified value. This should only be
2908 /// used by the SelectionDAG class.
2909 void SDNode::MorphNodeTo(unsigned Opc, SDVTList L,
2910 const SDOperand *Ops, unsigned NumOps) {
2913 NumValues = L.NumVTs;
2915 // Clear the operands list, updating used nodes to remove this from their
2917 for (op_iterator I = op_begin(), E = op_end(); I != E; ++I)
2918 I->Val->removeUser(this);
2920 // If NumOps is larger than the # of operands we currently have, reallocate
2921 // the operand list.
2922 if (NumOps > NumOperands) {
2923 if (OperandsNeedDelete)
2924 delete [] OperandList;
2925 OperandList = new SDOperand[NumOps];
2926 OperandsNeedDelete = true;
2929 // Assign the new operands.
2930 NumOperands = NumOps;
2932 for (unsigned i = 0, e = NumOps; i != e; ++i) {
2933 OperandList[i] = Ops[i];
2934 SDNode *N = OperandList[i].Val;
2935 N->Uses.push_back(this);
2939 /// SelectNodeTo - These are used for target selectors to *mutate* the
2940 /// specified node to have the specified return type, Target opcode, and
2941 /// operands. Note that target opcodes are stored as
2942 /// ISD::BUILTIN_OP_END+TargetOpcode in the node opcode field.
2944 /// Note that SelectNodeTo returns the resultant node. If there is already a
2945 /// node of the specified opcode and operands, it returns that node instead of
2946 /// the current one.
2947 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
2948 MVT::ValueType VT) {
2949 SDVTList VTs = getVTList(VT);
2950 FoldingSetNodeID ID;
2951 AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, 0, 0);
2953 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
2956 RemoveNodeFromCSEMaps(N);
2958 N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, 0, 0);
2960 CSEMap.InsertNode(N, IP);
2964 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
2965 MVT::ValueType VT, SDOperand Op1) {
2966 // If an identical node already exists, use it.
2967 SDVTList VTs = getVTList(VT);
2968 SDOperand Ops[] = { Op1 };
2970 FoldingSetNodeID ID;
2971 AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 1);
2973 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
2976 RemoveNodeFromCSEMaps(N);
2977 N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 1);
2978 CSEMap.InsertNode(N, IP);
2982 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
2983 MVT::ValueType VT, SDOperand Op1,
2985 // If an identical node already exists, use it.
2986 SDVTList VTs = getVTList(VT);
2987 SDOperand Ops[] = { Op1, Op2 };
2989 FoldingSetNodeID ID;
2990 AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 2);
2992 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
2995 RemoveNodeFromCSEMaps(N);
2997 N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 2);
2999 CSEMap.InsertNode(N, IP); // Memoize the new node.
3003 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3004 MVT::ValueType VT, SDOperand Op1,
3005 SDOperand Op2, SDOperand Op3) {
3006 // If an identical node already exists, use it.
3007 SDVTList VTs = getVTList(VT);
3008 SDOperand Ops[] = { Op1, Op2, Op3 };
3009 FoldingSetNodeID ID;
3010 AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 3);
3012 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3015 RemoveNodeFromCSEMaps(N);
3017 N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 3);
3019 CSEMap.InsertNode(N, IP); // Memoize the new node.
3023 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3024 MVT::ValueType VT, const SDOperand *Ops,
3026 // If an identical node already exists, use it.
3027 SDVTList VTs = getVTList(VT);
3028 FoldingSetNodeID ID;
3029 AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, NumOps);
3031 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3034 RemoveNodeFromCSEMaps(N);
3035 N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, NumOps);
3037 CSEMap.InsertNode(N, IP); // Memoize the new node.
3041 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3042 MVT::ValueType VT1, MVT::ValueType VT2,
3043 SDOperand Op1, SDOperand Op2) {
3044 SDVTList VTs = getVTList(VT1, VT2);
3045 FoldingSetNodeID ID;
3046 SDOperand Ops[] = { Op1, Op2 };
3047 AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 2);
3049 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3052 RemoveNodeFromCSEMaps(N);
3053 N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 2);
3054 CSEMap.InsertNode(N, IP); // Memoize the new node.
3058 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3059 MVT::ValueType VT1, MVT::ValueType VT2,
3060 SDOperand Op1, SDOperand Op2,
3062 // If an identical node already exists, use it.
3063 SDVTList VTs = getVTList(VT1, VT2);
3064 SDOperand Ops[] = { Op1, Op2, Op3 };
3065 FoldingSetNodeID ID;
3066 AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 3);
3068 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3071 RemoveNodeFromCSEMaps(N);
3073 N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 3);
3074 CSEMap.InsertNode(N, IP); // Memoize the new node.
3079 /// getTargetNode - These are used for target selectors to create a new node
3080 /// with specified return type(s), target opcode, and operands.
3082 /// Note that getTargetNode returns the resultant node. If there is already a
3083 /// node of the specified opcode and operands, it returns that node instead of
3084 /// the current one.
3085 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT) {
3086 return getNode(ISD::BUILTIN_OP_END+Opcode, VT).Val;
3088 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
3090 return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1).Val;
3092 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
3093 SDOperand Op1, SDOperand Op2) {
3094 return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1, Op2).Val;
3096 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
3097 SDOperand Op1, SDOperand Op2,
3099 return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1, Op2, Op3).Val;
3101 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
3102 const SDOperand *Ops, unsigned NumOps) {
3103 return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Ops, NumOps).Val;
3105 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3106 MVT::ValueType VT2) {
3107 const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2);
3109 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, &Op, 0).Val;
3111 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3112 MVT::ValueType VT2, SDOperand Op1) {
3113 const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2);
3114 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, &Op1, 1).Val;
3116 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3117 MVT::ValueType VT2, SDOperand Op1,
3119 const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2);
3120 SDOperand Ops[] = { Op1, Op2 };
3121 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, Ops, 2).Val;
3123 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3124 MVT::ValueType VT2, SDOperand Op1,
3125 SDOperand Op2, SDOperand Op3) {
3126 const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2);
3127 SDOperand Ops[] = { Op1, Op2, Op3 };
3128 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, Ops, 3).Val;
3130 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3132 const SDOperand *Ops, unsigned NumOps) {
3133 const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2);
3134 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, Ops, NumOps).Val;
3136 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3137 MVT::ValueType VT2, MVT::ValueType VT3,
3138 SDOperand Op1, SDOperand Op2) {
3139 const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2, VT3);
3140 SDOperand Ops[] = { Op1, Op2 };
3141 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 3, Ops, 2).Val;
3143 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3144 MVT::ValueType VT2, MVT::ValueType VT3,
3145 SDOperand Op1, SDOperand Op2,
3147 const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2, VT3);
3148 SDOperand Ops[] = { Op1, Op2, Op3 };
3149 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 3, Ops, 3).Val;
3151 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3152 MVT::ValueType VT2, MVT::ValueType VT3,
3153 const SDOperand *Ops, unsigned NumOps) {
3154 const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2, VT3);
3155 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 3, Ops, NumOps).Val;
3157 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3158 MVT::ValueType VT2, MVT::ValueType VT3,
3160 const SDOperand *Ops, unsigned NumOps) {
3161 std::vector<MVT::ValueType> VTList;
3162 VTList.push_back(VT1);
3163 VTList.push_back(VT2);
3164 VTList.push_back(VT3);
3165 VTList.push_back(VT4);
3166 const MVT::ValueType *VTs = getNodeValueTypes(VTList);
3167 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 4, Ops, NumOps).Val;
3169 SDNode *SelectionDAG::getTargetNode(unsigned Opcode,
3170 std::vector<MVT::ValueType> &ResultTys,
3171 const SDOperand *Ops, unsigned NumOps) {
3172 const MVT::ValueType *VTs = getNodeValueTypes(ResultTys);
3173 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, ResultTys.size(),
3177 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
3178 /// This can cause recursive merging of nodes in the DAG.
3180 /// This version assumes From/To have a single result value.
3182 void SelectionDAG::ReplaceAllUsesWith(SDOperand FromN, SDOperand ToN,
3183 std::vector<SDNode*> *Deleted) {
3184 SDNode *From = FromN.Val, *To = ToN.Val;
3185 assert(From->getNumValues() == 1 && To->getNumValues() == 1 &&
3186 "Cannot replace with this method!");
3187 assert(From != To && "Cannot replace uses of with self");
3189 while (!From->use_empty()) {
3190 // Process users until they are all gone.
3191 SDNode *U = *From->use_begin();
3193 // This node is about to morph, remove its old self from the CSE maps.
3194 RemoveNodeFromCSEMaps(U);
3196 for (SDOperand *I = U->OperandList, *E = U->OperandList+U->NumOperands;
3198 if (I->Val == From) {
3199 From->removeUser(U);
3204 // Now that we have modified U, add it back to the CSE maps. If it already
3205 // exists there, recursively merge the results together.
3206 if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
3207 ReplaceAllUsesWith(U, Existing, Deleted);
3209 if (Deleted) Deleted->push_back(U);
3210 DeleteNodeNotInCSEMaps(U);
3215 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
3216 /// This can cause recursive merging of nodes in the DAG.
3218 /// This version assumes From/To have matching types and numbers of result
3221 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To,
3222 std::vector<SDNode*> *Deleted) {
3223 assert(From != To && "Cannot replace uses of with self");
3224 assert(From->getNumValues() == To->getNumValues() &&
3225 "Cannot use this version of ReplaceAllUsesWith!");
3226 if (From->getNumValues() == 1) { // If possible, use the faster version.
3227 ReplaceAllUsesWith(SDOperand(From, 0), SDOperand(To, 0), Deleted);
3231 while (!From->use_empty()) {
3232 // Process users until they are all gone.
3233 SDNode *U = *From->use_begin();
3235 // This node is about to morph, remove its old self from the CSE maps.
3236 RemoveNodeFromCSEMaps(U);
3238 for (SDOperand *I = U->OperandList, *E = U->OperandList+U->NumOperands;
3240 if (I->Val == From) {
3241 From->removeUser(U);
3246 // Now that we have modified U, add it back to the CSE maps. If it already
3247 // exists there, recursively merge the results together.
3248 if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
3249 ReplaceAllUsesWith(U, Existing, Deleted);
3251 if (Deleted) Deleted->push_back(U);
3252 DeleteNodeNotInCSEMaps(U);
3257 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
3258 /// This can cause recursive merging of nodes in the DAG.
3260 /// This version can replace From with any result values. To must match the
3261 /// number and types of values returned by From.
3262 void SelectionDAG::ReplaceAllUsesWith(SDNode *From,
3263 const SDOperand *To,
3264 std::vector<SDNode*> *Deleted) {
3265 if (From->getNumValues() == 1 && To[0].Val->getNumValues() == 1) {
3266 // Degenerate case handled above.
3267 ReplaceAllUsesWith(SDOperand(From, 0), To[0], Deleted);
3271 while (!From->use_empty()) {
3272 // Process users until they are all gone.
3273 SDNode *U = *From->use_begin();
3275 // This node is about to morph, remove its old self from the CSE maps.
3276 RemoveNodeFromCSEMaps(U);
3278 for (SDOperand *I = U->OperandList, *E = U->OperandList+U->NumOperands;
3280 if (I->Val == From) {
3281 const SDOperand &ToOp = To[I->ResNo];
3282 From->removeUser(U);
3284 ToOp.Val->addUser(U);
3287 // Now that we have modified U, add it back to the CSE maps. If it already
3288 // exists there, recursively merge the results together.
3289 if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
3290 ReplaceAllUsesWith(U, Existing, Deleted);
3292 if (Deleted) Deleted->push_back(U);
3293 DeleteNodeNotInCSEMaps(U);
3298 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
3299 /// uses of other values produced by From.Val alone. The Deleted vector is
3300 /// handled the same was as for ReplaceAllUsesWith.
3301 void SelectionDAG::ReplaceAllUsesOfValueWith(SDOperand From, SDOperand To,
3302 std::vector<SDNode*> *Deleted) {
3303 assert(From != To && "Cannot replace a value with itself");
3304 // Handle the simple, trivial, case efficiently.
3305 if (From.Val->getNumValues() == 1 && To.Val->getNumValues() == 1) {
3306 ReplaceAllUsesWith(From, To, Deleted);
3310 // Get all of the users of From.Val. We want these in a nice,
3311 // deterministically ordered and uniqued set, so we use a SmallSetVector.
3312 SmallSetVector<SDNode*, 16> Users(From.Val->use_begin(), From.Val->use_end());
3314 std::vector<SDNode*> LocalDeletionVector;
3316 // Pick a deletion vector to use. If the user specified one, use theirs,
3317 // otherwise use a local one.
3318 std::vector<SDNode*> *DeleteVector = Deleted ? Deleted : &LocalDeletionVector;
3319 while (!Users.empty()) {
3320 // We know that this user uses some value of From. If it is the right
3321 // value, update it.
3322 SDNode *User = Users.back();
3325 // Scan for an operand that matches From.
3326 SDOperand *Op = User->OperandList, *E = User->OperandList+User->NumOperands;
3327 for (; Op != E; ++Op)
3328 if (*Op == From) break;
3330 // If there are no matches, the user must use some other result of From.
3331 if (Op == E) continue;
3333 // Okay, we know this user needs to be updated. Remove its old self
3334 // from the CSE maps.
3335 RemoveNodeFromCSEMaps(User);
3337 // Update all operands that match "From".
3338 for (; Op != E; ++Op) {
3340 From.Val->removeUser(User);
3342 To.Val->addUser(User);
3346 // Now that we have modified User, add it back to the CSE maps. If it
3347 // already exists there, recursively merge the results together.
3348 SDNode *Existing = AddNonLeafNodeToCSEMaps(User);
3349 if (!Existing) continue; // Continue on to next user.
3351 // If there was already an existing matching node, use ReplaceAllUsesWith
3352 // to replace the dead one with the existing one. However, this can cause
3353 // recursive merging of other unrelated nodes down the line. The merging
3354 // can cause deletion of nodes that used the old value. In this case,
3355 // we have to be certain to remove them from the Users set.
3356 unsigned NumDeleted = DeleteVector->size();
3357 ReplaceAllUsesWith(User, Existing, DeleteVector);
3359 // User is now dead.
3360 DeleteVector->push_back(User);
3361 DeleteNodeNotInCSEMaps(User);
3363 // We have to be careful here, because ReplaceAllUsesWith could have
3364 // deleted a user of From, which means there may be dangling pointers
3365 // in the "Users" setvector. Scan over the deleted node pointers and
3366 // remove them from the setvector.
3367 for (unsigned i = NumDeleted, e = DeleteVector->size(); i != e; ++i)
3368 Users.remove((*DeleteVector)[i]);
3370 // If the user doesn't need the set of deleted elements, don't retain them
3371 // to the next loop iteration.
3373 LocalDeletionVector.clear();
3378 /// AssignNodeIds - Assign a unique node id for each node in the DAG based on
3379 /// their allnodes order. It returns the maximum id.
3380 unsigned SelectionDAG::AssignNodeIds() {
3382 for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I){
3389 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
3390 /// based on their topological order. It returns the maximum id and a vector
3391 /// of the SDNodes* in assigned order by reference.
3392 unsigned SelectionDAG::AssignTopologicalOrder(std::vector<SDNode*> &TopOrder) {
3393 unsigned DAGSize = AllNodes.size();
3394 std::vector<unsigned> InDegree(DAGSize);
3395 std::vector<SDNode*> Sources;
3397 // Use a two pass approach to avoid using a std::map which is slow.
3399 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ++I){
3402 unsigned Degree = N->use_size();
3403 InDegree[N->getNodeId()] = Degree;
3405 Sources.push_back(N);
3409 while (!Sources.empty()) {
3410 SDNode *N = Sources.back();
3412 TopOrder.push_back(N);
3413 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
3415 unsigned Degree = --InDegree[P->getNodeId()];
3417 Sources.push_back(P);
3421 // Second pass, assign the actual topological order as node ids.
3423 for (std::vector<SDNode*>::iterator TI = TopOrder.begin(),TE = TopOrder.end();
3425 (*TI)->setNodeId(Id++);
3432 //===----------------------------------------------------------------------===//
3434 //===----------------------------------------------------------------------===//
3436 // Out-of-line virtual method to give class a home.
3437 void SDNode::ANCHOR() {}
3438 void UnarySDNode::ANCHOR() {}
3439 void BinarySDNode::ANCHOR() {}
3440 void TernarySDNode::ANCHOR() {}
3441 void HandleSDNode::ANCHOR() {}
3442 void StringSDNode::ANCHOR() {}
3443 void ConstantSDNode::ANCHOR() {}
3444 void ConstantFPSDNode::ANCHOR() {}
3445 void GlobalAddressSDNode::ANCHOR() {}
3446 void FrameIndexSDNode::ANCHOR() {}
3447 void JumpTableSDNode::ANCHOR() {}
3448 void ConstantPoolSDNode::ANCHOR() {}
3449 void BasicBlockSDNode::ANCHOR() {}
3450 void SrcValueSDNode::ANCHOR() {}
3451 void MemOperandSDNode::ANCHOR() {}
3452 void RegisterSDNode::ANCHOR() {}
3453 void ExternalSymbolSDNode::ANCHOR() {}
3454 void CondCodeSDNode::ANCHOR() {}
3455 void VTSDNode::ANCHOR() {}
3456 void LoadSDNode::ANCHOR() {}
3457 void StoreSDNode::ANCHOR() {}
3459 HandleSDNode::~HandleSDNode() {
3460 SDVTList VTs = { 0, 0 };
3461 MorphNodeTo(ISD::HANDLENODE, VTs, 0, 0); // Drops operand uses.
3464 GlobalAddressSDNode::GlobalAddressSDNode(bool isTarget, const GlobalValue *GA,
3465 MVT::ValueType VT, int o)
3466 : SDNode(isa<GlobalVariable>(GA) &&
3467 cast<GlobalVariable>(GA)->isThreadLocal() ?
3469 (isTarget ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress) :
3471 (isTarget ? ISD::TargetGlobalAddress : ISD::GlobalAddress),
3472 getSDVTList(VT)), Offset(o) {
3473 TheGlobal = const_cast<GlobalValue*>(GA);
3476 /// getMemOperand - Return a MemOperand object describing the memory
3477 /// reference performed by this load or store.
3478 MemOperand LSBaseSDNode::getMemOperand() const {
3479 int Size = (MVT::getSizeInBits(getMemoryVT()) + 7) >> 3;
3481 getOpcode() == ISD::LOAD ? MemOperand::MOLoad : MemOperand::MOStore;
3482 if (IsVolatile) Flags |= MemOperand::MOVolatile;
3484 // Check if the load references a frame index, and does not have
3486 const FrameIndexSDNode *FI =
3487 dyn_cast<const FrameIndexSDNode>(getBasePtr().Val);
3488 if (!getSrcValue() && FI)
3489 return MemOperand(&PseudoSourceValue::FPRel, Flags,
3490 FI->getIndex(), Size, Alignment);
3492 return MemOperand(getSrcValue(), Flags,
3493 getSrcValueOffset(), Size, Alignment);
3496 /// Profile - Gather unique data for the node.
3498 void SDNode::Profile(FoldingSetNodeID &ID) {
3499 AddNodeIDNode(ID, this);
3502 /// getValueTypeList - Return a pointer to the specified value type.
3504 MVT::ValueType *SDNode::getValueTypeList(MVT::ValueType VT) {
3505 if (MVT::isExtendedVT(VT)) {
3506 static std::set<MVT::ValueType> EVTs;
3507 return (MVT::ValueType *)&(*EVTs.insert(VT).first);
3509 static MVT::ValueType VTs[MVT::LAST_VALUETYPE];
3515 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
3516 /// indicated value. This method ignores uses of other values defined by this
3518 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
3519 assert(Value < getNumValues() && "Bad value!");
3521 // If there is only one value, this is easy.
3522 if (getNumValues() == 1)
3523 return use_size() == NUses;
3524 if (use_size() < NUses) return false;
3526 SDOperand TheValue(const_cast<SDNode *>(this), Value);
3528 SmallPtrSet<SDNode*, 32> UsersHandled;
3530 for (SDNode::use_iterator UI = Uses.begin(), E = Uses.end(); UI != E; ++UI) {
3532 if (User->getNumOperands() == 1 ||
3533 UsersHandled.insert(User)) // First time we've seen this?
3534 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
3535 if (User->getOperand(i) == TheValue) {
3537 return false; // too many uses
3542 // Found exactly the right number of uses?
3547 /// hasAnyUseOfValue - Return true if there are any use of the indicated
3548 /// value. This method ignores uses of other values defined by this operation.
3549 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
3550 assert(Value < getNumValues() && "Bad value!");
3552 if (use_empty()) return false;
3554 SDOperand TheValue(const_cast<SDNode *>(this), Value);
3556 SmallPtrSet<SDNode*, 32> UsersHandled;
3558 for (SDNode::use_iterator UI = Uses.begin(), E = Uses.end(); UI != E; ++UI) {
3560 if (User->getNumOperands() == 1 ||
3561 UsersHandled.insert(User)) // First time we've seen this?
3562 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
3563 if (User->getOperand(i) == TheValue) {
3572 /// isOnlyUse - Return true if this node is the only use of N.
3574 bool SDNode::isOnlyUse(SDNode *N) const {
3576 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
3587 /// isOperand - Return true if this node is an operand of N.
3589 bool SDOperand::isOperand(SDNode *N) const {
3590 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
3591 if (*this == N->getOperand(i))
3596 bool SDNode::isOperand(SDNode *N) const {
3597 for (unsigned i = 0, e = N->NumOperands; i != e; ++i)
3598 if (this == N->OperandList[i].Val)
3603 /// reachesChainWithoutSideEffects - Return true if this operand (which must
3604 /// be a chain) reaches the specified operand without crossing any
3605 /// side-effecting instructions. In practice, this looks through token
3606 /// factors and non-volatile loads. In order to remain efficient, this only
3607 /// looks a couple of nodes in, it does not do an exhaustive search.
3608 bool SDOperand::reachesChainWithoutSideEffects(SDOperand Dest,
3609 unsigned Depth) const {
3610 if (*this == Dest) return true;
3612 // Don't search too deeply, we just want to be able to see through
3613 // TokenFactor's etc.
3614 if (Depth == 0) return false;
3616 // If this is a token factor, all inputs to the TF happen in parallel. If any
3617 // of the operands of the TF reach dest, then we can do the xform.
3618 if (getOpcode() == ISD::TokenFactor) {
3619 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
3620 if (getOperand(i).reachesChainWithoutSideEffects(Dest, Depth-1))
3625 // Loads don't have side effects, look through them.
3626 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
3627 if (!Ld->isVolatile())
3628 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
3634 static void findPredecessor(SDNode *N, const SDNode *P, bool &found,
3635 SmallPtrSet<SDNode *, 32> &Visited) {
3636 if (found || !Visited.insert(N))
3639 for (unsigned i = 0, e = N->getNumOperands(); !found && i != e; ++i) {
3640 SDNode *Op = N->getOperand(i).Val;
3645 findPredecessor(Op, P, found, Visited);
3649 /// isPredecessor - Return true if this node is a predecessor of N. This node
3650 /// is either an operand of N or it can be reached by recursively traversing
3651 /// up the operands.
3652 /// NOTE: this is an expensive method. Use it carefully.
3653 bool SDNode::isPredecessor(SDNode *N) const {
3654 SmallPtrSet<SDNode *, 32> Visited;
3656 findPredecessor(N, this, found, Visited);
3660 uint64_t SDNode::getConstantOperandVal(unsigned Num) const {
3661 assert(Num < NumOperands && "Invalid child # of SDNode!");
3662 return cast<ConstantSDNode>(OperandList[Num])->getValue();
3665 std::string SDNode::getOperationName(const SelectionDAG *G) const {
3666 switch (getOpcode()) {
3668 if (getOpcode() < ISD::BUILTIN_OP_END)
3669 return "<<Unknown DAG Node>>";
3672 if (const TargetInstrInfo *TII = G->getTarget().getInstrInfo())
3673 if (getOpcode()-ISD::BUILTIN_OP_END < TII->getNumOpcodes())
3674 return TII->get(getOpcode()-ISD::BUILTIN_OP_END).getName();
3676 TargetLowering &TLI = G->getTargetLoweringInfo();
3678 TLI.getTargetNodeName(getOpcode());
3679 if (Name) return Name;
3682 return "<<Unknown Target Node>>";
3685 case ISD::PCMARKER: return "PCMarker";
3686 case ISD::READCYCLECOUNTER: return "ReadCycleCounter";
3687 case ISD::SRCVALUE: return "SrcValue";
3688 case ISD::MEMOPERAND: return "MemOperand";
3689 case ISD::EntryToken: return "EntryToken";
3690 case ISD::TokenFactor: return "TokenFactor";
3691 case ISD::AssertSext: return "AssertSext";
3692 case ISD::AssertZext: return "AssertZext";
3694 case ISD::STRING: return "String";
3695 case ISD::BasicBlock: return "BasicBlock";
3696 case ISD::VALUETYPE: return "ValueType";
3697 case ISD::Register: return "Register";
3699 case ISD::Constant: return "Constant";
3700 case ISD::ConstantFP: return "ConstantFP";
3701 case ISD::GlobalAddress: return "GlobalAddress";
3702 case ISD::GlobalTLSAddress: return "GlobalTLSAddress";
3703 case ISD::FrameIndex: return "FrameIndex";
3704 case ISD::JumpTable: return "JumpTable";
3705 case ISD::GLOBAL_OFFSET_TABLE: return "GLOBAL_OFFSET_TABLE";
3706 case ISD::RETURNADDR: return "RETURNADDR";
3707 case ISD::FRAMEADDR: return "FRAMEADDR";
3708 case ISD::FRAME_TO_ARGS_OFFSET: return "FRAME_TO_ARGS_OFFSET";
3709 case ISD::EXCEPTIONADDR: return "EXCEPTIONADDR";
3710 case ISD::EHSELECTION: return "EHSELECTION";
3711 case ISD::EH_RETURN: return "EH_RETURN";
3712 case ISD::ConstantPool: return "ConstantPool";
3713 case ISD::ExternalSymbol: return "ExternalSymbol";
3714 case ISD::INTRINSIC_WO_CHAIN: {
3715 unsigned IID = cast<ConstantSDNode>(getOperand(0))->getValue();
3716 return Intrinsic::getName((Intrinsic::ID)IID);
3718 case ISD::INTRINSIC_VOID:
3719 case ISD::INTRINSIC_W_CHAIN: {
3720 unsigned IID = cast<ConstantSDNode>(getOperand(1))->getValue();
3721 return Intrinsic::getName((Intrinsic::ID)IID);
3724 case ISD::BUILD_VECTOR: return "BUILD_VECTOR";
3725 case ISD::TargetConstant: return "TargetConstant";
3726 case ISD::TargetConstantFP:return "TargetConstantFP";
3727 case ISD::TargetGlobalAddress: return "TargetGlobalAddress";
3728 case ISD::TargetGlobalTLSAddress: return "TargetGlobalTLSAddress";
3729 case ISD::TargetFrameIndex: return "TargetFrameIndex";
3730 case ISD::TargetJumpTable: return "TargetJumpTable";
3731 case ISD::TargetConstantPool: return "TargetConstantPool";
3732 case ISD::TargetExternalSymbol: return "TargetExternalSymbol";
3734 case ISD::CopyToReg: return "CopyToReg";
3735 case ISD::CopyFromReg: return "CopyFromReg";
3736 case ISD::UNDEF: return "undef";
3737 case ISD::MERGE_VALUES: return "merge_values";
3738 case ISD::INLINEASM: return "inlineasm";
3739 case ISD::LABEL: return "label";
3740 case ISD::HANDLENODE: return "handlenode";
3741 case ISD::FORMAL_ARGUMENTS: return "formal_arguments";
3742 case ISD::CALL: return "call";
3745 case ISD::FABS: return "fabs";
3746 case ISD::FNEG: return "fneg";
3747 case ISD::FSQRT: return "fsqrt";
3748 case ISD::FSIN: return "fsin";
3749 case ISD::FCOS: return "fcos";
3750 case ISD::FPOWI: return "fpowi";
3751 case ISD::FPOW: return "fpow";
3754 case ISD::ADD: return "add";
3755 case ISD::SUB: return "sub";
3756 case ISD::MUL: return "mul";
3757 case ISD::MULHU: return "mulhu";
3758 case ISD::MULHS: return "mulhs";
3759 case ISD::SDIV: return "sdiv";
3760 case ISD::UDIV: return "udiv";
3761 case ISD::SREM: return "srem";
3762 case ISD::UREM: return "urem";
3763 case ISD::SMUL_LOHI: return "smul_lohi";
3764 case ISD::UMUL_LOHI: return "umul_lohi";
3765 case ISD::SDIVREM: return "sdivrem";
3766 case ISD::UDIVREM: return "divrem";
3767 case ISD::AND: return "and";
3768 case ISD::OR: return "or";
3769 case ISD::XOR: return "xor";
3770 case ISD::SHL: return "shl";
3771 case ISD::SRA: return "sra";
3772 case ISD::SRL: return "srl";
3773 case ISD::ROTL: return "rotl";
3774 case ISD::ROTR: return "rotr";
3775 case ISD::FADD: return "fadd";
3776 case ISD::FSUB: return "fsub";
3777 case ISD::FMUL: return "fmul";
3778 case ISD::FDIV: return "fdiv";
3779 case ISD::FREM: return "frem";
3780 case ISD::FCOPYSIGN: return "fcopysign";
3781 case ISD::FGETSIGN: return "fgetsign";
3783 case ISD::SETCC: return "setcc";
3784 case ISD::SELECT: return "select";
3785 case ISD::SELECT_CC: return "select_cc";
3786 case ISD::INSERT_VECTOR_ELT: return "insert_vector_elt";
3787 case ISD::EXTRACT_VECTOR_ELT: return "extract_vector_elt";
3788 case ISD::CONCAT_VECTORS: return "concat_vectors";
3789 case ISD::EXTRACT_SUBVECTOR: return "extract_subvector";
3790 case ISD::SCALAR_TO_VECTOR: return "scalar_to_vector";
3791 case ISD::VECTOR_SHUFFLE: return "vector_shuffle";
3792 case ISD::CARRY_FALSE: return "carry_false";
3793 case ISD::ADDC: return "addc";
3794 case ISD::ADDE: return "adde";
3795 case ISD::SUBC: return "subc";
3796 case ISD::SUBE: return "sube";
3797 case ISD::SHL_PARTS: return "shl_parts";
3798 case ISD::SRA_PARTS: return "sra_parts";
3799 case ISD::SRL_PARTS: return "srl_parts";
3801 case ISD::EXTRACT_SUBREG: return "extract_subreg";
3802 case ISD::INSERT_SUBREG: return "insert_subreg";
3804 // Conversion operators.
3805 case ISD::SIGN_EXTEND: return "sign_extend";
3806 case ISD::ZERO_EXTEND: return "zero_extend";
3807 case ISD::ANY_EXTEND: return "any_extend";
3808 case ISD::SIGN_EXTEND_INREG: return "sign_extend_inreg";
3809 case ISD::TRUNCATE: return "truncate";
3810 case ISD::FP_ROUND: return "fp_round";
3811 case ISD::FLT_ROUNDS_: return "flt_rounds";
3812 case ISD::FP_ROUND_INREG: return "fp_round_inreg";
3813 case ISD::FP_EXTEND: return "fp_extend";
3815 case ISD::SINT_TO_FP: return "sint_to_fp";
3816 case ISD::UINT_TO_FP: return "uint_to_fp";
3817 case ISD::FP_TO_SINT: return "fp_to_sint";
3818 case ISD::FP_TO_UINT: return "fp_to_uint";
3819 case ISD::BIT_CONVERT: return "bit_convert";
3821 // Control flow instructions
3822 case ISD::BR: return "br";
3823 case ISD::BRIND: return "brind";
3824 case ISD::BR_JT: return "br_jt";
3825 case ISD::BRCOND: return "brcond";
3826 case ISD::BR_CC: return "br_cc";
3827 case ISD::RET: return "ret";
3828 case ISD::CALLSEQ_START: return "callseq_start";
3829 case ISD::CALLSEQ_END: return "callseq_end";
3832 case ISD::LOAD: return "load";
3833 case ISD::STORE: return "store";
3834 case ISD::VAARG: return "vaarg";
3835 case ISD::VACOPY: return "vacopy";
3836 case ISD::VAEND: return "vaend";
3837 case ISD::VASTART: return "vastart";
3838 case ISD::DYNAMIC_STACKALLOC: return "dynamic_stackalloc";
3839 case ISD::EXTRACT_ELEMENT: return "extract_element";
3840 case ISD::BUILD_PAIR: return "build_pair";
3841 case ISD::STACKSAVE: return "stacksave";
3842 case ISD::STACKRESTORE: return "stackrestore";
3843 case ISD::TRAP: return "trap";
3845 // Block memory operations.
3846 case ISD::MEMSET: return "memset";
3847 case ISD::MEMCPY: return "memcpy";
3848 case ISD::MEMMOVE: return "memmove";
3851 case ISD::BSWAP: return "bswap";
3852 case ISD::CTPOP: return "ctpop";
3853 case ISD::CTTZ: return "cttz";
3854 case ISD::CTLZ: return "ctlz";
3857 case ISD::LOCATION: return "location";
3858 case ISD::DEBUG_LOC: return "debug_loc";
3861 case ISD::TRAMPOLINE: return "trampoline";
3864 switch (cast<CondCodeSDNode>(this)->get()) {
3865 default: assert(0 && "Unknown setcc condition!");
3866 case ISD::SETOEQ: return "setoeq";
3867 case ISD::SETOGT: return "setogt";
3868 case ISD::SETOGE: return "setoge";
3869 case ISD::SETOLT: return "setolt";
3870 case ISD::SETOLE: return "setole";
3871 case ISD::SETONE: return "setone";
3873 case ISD::SETO: return "seto";
3874 case ISD::SETUO: return "setuo";
3875 case ISD::SETUEQ: return "setue";
3876 case ISD::SETUGT: return "setugt";
3877 case ISD::SETUGE: return "setuge";
3878 case ISD::SETULT: return "setult";
3879 case ISD::SETULE: return "setule";
3880 case ISD::SETUNE: return "setune";
3882 case ISD::SETEQ: return "seteq";
3883 case ISD::SETGT: return "setgt";
3884 case ISD::SETGE: return "setge";
3885 case ISD::SETLT: return "setlt";
3886 case ISD::SETLE: return "setle";
3887 case ISD::SETNE: return "setne";
3892 const char *SDNode::getIndexedModeName(ISD::MemIndexedMode AM) {
3901 return "<post-inc>";
3903 return "<post-dec>";
3907 void SDNode::dump() const { dump(0); }
3908 void SDNode::dump(const SelectionDAG *G) const {
3909 cerr << (void*)this << ": ";
3911 for (unsigned i = 0, e = getNumValues(); i != e; ++i) {
3913 if (getValueType(i) == MVT::Other)
3916 cerr << MVT::getValueTypeString(getValueType(i));
3918 cerr << " = " << getOperationName(G);
3921 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
3922 if (i) cerr << ", ";
3923 cerr << (void*)getOperand(i).Val;
3924 if (unsigned RN = getOperand(i).ResNo)
3928 if (!isTargetOpcode() && getOpcode() == ISD::VECTOR_SHUFFLE) {
3929 SDNode *Mask = getOperand(2).Val;
3931 for (unsigned i = 0, e = Mask->getNumOperands(); i != e; ++i) {
3933 if (Mask->getOperand(i).getOpcode() == ISD::UNDEF)
3936 cerr << cast<ConstantSDNode>(Mask->getOperand(i))->getValue();
3941 if (const ConstantSDNode *CSDN = dyn_cast<ConstantSDNode>(this)) {
3942 cerr << "<" << CSDN->getValue() << ">";
3943 } else if (const ConstantFPSDNode *CSDN = dyn_cast<ConstantFPSDNode>(this)) {
3944 if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEsingle)
3945 cerr << "<" << CSDN->getValueAPF().convertToFloat() << ">";
3946 else if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEdouble)
3947 cerr << "<" << CSDN->getValueAPF().convertToDouble() << ">";
3949 cerr << "<APFloat(";
3950 CSDN->getValueAPF().convertToAPInt().dump();
3953 } else if (const GlobalAddressSDNode *GADN =
3954 dyn_cast<GlobalAddressSDNode>(this)) {
3955 int offset = GADN->getOffset();
3957 WriteAsOperand(*cerr.stream(), GADN->getGlobal()) << ">";
3959 cerr << " + " << offset;
3961 cerr << " " << offset;
3962 } else if (const FrameIndexSDNode *FIDN = dyn_cast<FrameIndexSDNode>(this)) {
3963 cerr << "<" << FIDN->getIndex() << ">";
3964 } else if (const JumpTableSDNode *JTDN = dyn_cast<JumpTableSDNode>(this)) {
3965 cerr << "<" << JTDN->getIndex() << ">";
3966 } else if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(this)){
3967 int offset = CP->getOffset();
3968 if (CP->isMachineConstantPoolEntry())
3969 cerr << "<" << *CP->getMachineCPVal() << ">";
3971 cerr << "<" << *CP->getConstVal() << ">";
3973 cerr << " + " << offset;
3975 cerr << " " << offset;
3976 } else if (const BasicBlockSDNode *BBDN = dyn_cast<BasicBlockSDNode>(this)) {
3978 const Value *LBB = (const Value*)BBDN->getBasicBlock()->getBasicBlock();
3980 cerr << LBB->getName() << " ";
3981 cerr << (const void*)BBDN->getBasicBlock() << ">";
3982 } else if (const RegisterSDNode *R = dyn_cast<RegisterSDNode>(this)) {
3983 if (G && R->getReg() && MRegisterInfo::isPhysicalRegister(R->getReg())) {
3984 cerr << " " <<G->getTarget().getRegisterInfo()->getName(R->getReg());
3986 cerr << " #" << R->getReg();
3988 } else if (const ExternalSymbolSDNode *ES =
3989 dyn_cast<ExternalSymbolSDNode>(this)) {
3990 cerr << "'" << ES->getSymbol() << "'";
3991 } else if (const SrcValueSDNode *M = dyn_cast<SrcValueSDNode>(this)) {
3993 cerr << "<" << M->getValue() << ">";
3996 } else if (const MemOperandSDNode *M = dyn_cast<MemOperandSDNode>(this)) {
3997 if (M->MO.getValue())
3998 cerr << "<" << M->MO.getValue() << ":" << M->MO.getOffset() << ">";
4000 cerr << "<null:" << M->MO.getOffset() << ">";
4001 } else if (const VTSDNode *N = dyn_cast<VTSDNode>(this)) {
4002 cerr << ":" << MVT::getValueTypeString(N->getVT());
4003 } else if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(this)) {
4004 const Value *SrcValue = LD->getSrcValue();
4005 int SrcOffset = LD->getSrcValueOffset();
4011 cerr << ":" << SrcOffset << ">";
4014 switch (LD->getExtensionType()) {
4015 default: doExt = false; break;
4017 cerr << " <anyext ";
4027 cerr << MVT::getValueTypeString(LD->getMemoryVT()) << ">";
4029 const char *AM = getIndexedModeName(LD->getAddressingMode());
4032 if (LD->isVolatile())
4033 cerr << " <volatile>";
4034 cerr << " alignment=" << LD->getAlignment();
4035 } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(this)) {
4036 const Value *SrcValue = ST->getSrcValue();
4037 int SrcOffset = ST->getSrcValueOffset();
4043 cerr << ":" << SrcOffset << ">";
4045 if (ST->isTruncatingStore())
4047 << MVT::getValueTypeString(ST->getMemoryVT()) << ">";
4049 const char *AM = getIndexedModeName(ST->getAddressingMode());
4052 if (ST->isVolatile())
4053 cerr << " <volatile>";
4054 cerr << " alignment=" << ST->getAlignment();
4058 static void DumpNodes(const SDNode *N, unsigned indent, const SelectionDAG *G) {
4059 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4060 if (N->getOperand(i).Val->hasOneUse())
4061 DumpNodes(N->getOperand(i).Val, indent+2, G);
4063 cerr << "\n" << std::string(indent+2, ' ')
4064 << (void*)N->getOperand(i).Val << ": <multiple use>";
4067 cerr << "\n" << std::string(indent, ' ');
4071 void SelectionDAG::dump() const {
4072 cerr << "SelectionDAG has " << AllNodes.size() << " nodes:";
4073 std::vector<const SDNode*> Nodes;
4074 for (allnodes_const_iterator I = allnodes_begin(), E = allnodes_end();
4078 std::sort(Nodes.begin(), Nodes.end());
4080 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
4081 if (!Nodes[i]->hasOneUse() && Nodes[i] != getRoot().Val)
4082 DumpNodes(Nodes[i], 2, this);
4085 if (getRoot().Val) DumpNodes(getRoot().Val, 2, this);
4090 const Type *ConstantPoolSDNode::getType() const {
4091 if (isMachineConstantPoolEntry())
4092 return Val.MachineCPVal->getType();
4093 return Val.ConstVal->getType();