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 //===----------------------------------------------------------------------===//
13 #include "llvm/CodeGen/SelectionDAG.h"
14 #include "llvm/Constants.h"
15 #include "llvm/Analysis/ValueTracking.h"
16 #include "llvm/GlobalAlias.h"
17 #include "llvm/GlobalVariable.h"
18 #include "llvm/Intrinsics.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Assembly/Writer.h"
21 #include "llvm/CallingConv.h"
22 #include "llvm/CodeGen/MachineBasicBlock.h"
23 #include "llvm/CodeGen/MachineConstantPool.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineModuleInfo.h"
26 #include "llvm/CodeGen/PseudoSourceValue.h"
27 #include "llvm/Support/MathExtras.h"
28 #include "llvm/Target/TargetRegisterInfo.h"
29 #include "llvm/Target/TargetData.h"
30 #include "llvm/Target/TargetLowering.h"
31 #include "llvm/Target/TargetInstrInfo.h"
32 #include "llvm/Target/TargetMachine.h"
33 #include "llvm/ADT/SetVector.h"
34 #include "llvm/ADT/SmallPtrSet.h"
35 #include "llvm/ADT/SmallSet.h"
36 #include "llvm/ADT/SmallVector.h"
37 #include "llvm/ADT/StringExtras.h"
42 /// makeVTList - Return an instance of the SDVTList struct initialized with the
43 /// specified members.
44 static SDVTList makeVTList(const MVT *VTs, unsigned NumVTs) {
45 SDVTList Res = {VTs, NumVTs};
49 static const fltSemantics *MVTToAPFloatSemantics(MVT VT) {
50 switch (VT.getSimpleVT()) {
51 default: assert(0 && "Unknown FP format");
52 case MVT::f32: return &APFloat::IEEEsingle;
53 case MVT::f64: return &APFloat::IEEEdouble;
54 case MVT::f80: return &APFloat::x87DoubleExtended;
55 case MVT::f128: return &APFloat::IEEEquad;
56 case MVT::ppcf128: return &APFloat::PPCDoubleDouble;
60 SelectionDAG::DAGUpdateListener::~DAGUpdateListener() {}
62 //===----------------------------------------------------------------------===//
63 // ConstantFPSDNode Class
64 //===----------------------------------------------------------------------===//
66 /// isExactlyValue - We don't rely on operator== working on double values, as
67 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
68 /// As such, this method can be used to do an exact bit-for-bit comparison of
69 /// two floating point values.
70 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
71 return Value.bitwiseIsEqual(V);
74 bool ConstantFPSDNode::isValueValidForType(MVT VT,
76 assert(VT.isFloatingPoint() && "Can only convert between FP types");
78 // PPC long double cannot be converted to any other type.
79 if (VT == MVT::ppcf128 ||
80 &Val.getSemantics() == &APFloat::PPCDoubleDouble)
83 // convert modifies in place, so make a copy.
84 APFloat Val2 = APFloat(Val);
85 return Val2.convert(*MVTToAPFloatSemantics(VT),
86 APFloat::rmNearestTiesToEven) == APFloat::opOK;
89 //===----------------------------------------------------------------------===//
91 //===----------------------------------------------------------------------===//
93 /// isBuildVectorAllOnes - Return true if the specified node is a
94 /// BUILD_VECTOR where all of the elements are ~0 or undef.
95 bool ISD::isBuildVectorAllOnes(const SDNode *N) {
96 // Look through a bit convert.
97 if (N->getOpcode() == ISD::BIT_CONVERT)
98 N = N->getOperand(0).Val;
100 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
102 unsigned i = 0, e = N->getNumOperands();
104 // Skip over all of the undef values.
105 while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
108 // Do not accept an all-undef vector.
109 if (i == e) return false;
111 // Do not accept build_vectors that aren't all constants or which have non-~0
113 SDOperand NotZero = N->getOperand(i);
114 if (isa<ConstantSDNode>(NotZero)) {
115 if (!cast<ConstantSDNode>(NotZero)->isAllOnesValue())
117 } else if (isa<ConstantFPSDNode>(NotZero)) {
118 if (!cast<ConstantFPSDNode>(NotZero)->getValueAPF().
119 convertToAPInt().isAllOnesValue())
124 // Okay, we have at least one ~0 value, check to see if the rest match or are
126 for (++i; i != e; ++i)
127 if (N->getOperand(i) != NotZero &&
128 N->getOperand(i).getOpcode() != ISD::UNDEF)
134 /// isBuildVectorAllZeros - Return true if the specified node is a
135 /// BUILD_VECTOR where all of the elements are 0 or undef.
136 bool ISD::isBuildVectorAllZeros(const SDNode *N) {
137 // Look through a bit convert.
138 if (N->getOpcode() == ISD::BIT_CONVERT)
139 N = N->getOperand(0).Val;
141 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
143 unsigned i = 0, e = N->getNumOperands();
145 // Skip over all of the undef values.
146 while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
149 // Do not accept an all-undef vector.
150 if (i == e) return false;
152 // Do not accept build_vectors that aren't all constants or which have non-~0
154 SDOperand Zero = N->getOperand(i);
155 if (isa<ConstantSDNode>(Zero)) {
156 if (!cast<ConstantSDNode>(Zero)->isNullValue())
158 } else if (isa<ConstantFPSDNode>(Zero)) {
159 if (!cast<ConstantFPSDNode>(Zero)->getValueAPF().isPosZero())
164 // Okay, we have at least one ~0 value, check to see if the rest match or are
166 for (++i; i != e; ++i)
167 if (N->getOperand(i) != Zero &&
168 N->getOperand(i).getOpcode() != ISD::UNDEF)
173 /// isScalarToVector - Return true if the specified node is a
174 /// ISD::SCALAR_TO_VECTOR node or a BUILD_VECTOR node where only the low
175 /// element is not an undef.
176 bool ISD::isScalarToVector(const SDNode *N) {
177 if (N->getOpcode() == ISD::SCALAR_TO_VECTOR)
180 if (N->getOpcode() != ISD::BUILD_VECTOR)
182 if (N->getOperand(0).getOpcode() == ISD::UNDEF)
184 unsigned NumElems = N->getNumOperands();
185 for (unsigned i = 1; i < NumElems; ++i) {
186 SDOperand V = N->getOperand(i);
187 if (V.getOpcode() != ISD::UNDEF)
194 /// isDebugLabel - Return true if the specified node represents a debug
195 /// label (i.e. ISD::DBG_LABEL or TargetInstrInfo::DBG_LABEL node).
196 bool ISD::isDebugLabel(const SDNode *N) {
198 if (N->getOpcode() == ISD::DBG_LABEL)
200 if (N->isTargetOpcode() &&
201 N->getTargetOpcode() == TargetInstrInfo::DBG_LABEL)
206 /// getSetCCSwappedOperands - Return the operation corresponding to (Y op X)
207 /// when given the operation for (X op Y).
208 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
209 // To perform this operation, we just need to swap the L and G bits of the
211 unsigned OldL = (Operation >> 2) & 1;
212 unsigned OldG = (Operation >> 1) & 1;
213 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits
214 (OldL << 1) | // New G bit
215 (OldG << 2)); // New L bit.
218 /// getSetCCInverse - Return the operation corresponding to !(X op Y), where
219 /// 'op' is a valid SetCC operation.
220 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, bool isInteger) {
221 unsigned Operation = Op;
223 Operation ^= 7; // Flip L, G, E bits, but not U.
225 Operation ^= 15; // Flip all of the condition bits.
226 if (Operation > ISD::SETTRUE2)
227 Operation &= ~8; // Don't let N and U bits get set.
228 return ISD::CondCode(Operation);
232 /// isSignedOp - For an integer comparison, return 1 if the comparison is a
233 /// signed operation and 2 if the result is an unsigned comparison. Return zero
234 /// if the operation does not depend on the sign of the input (setne and seteq).
235 static int isSignedOp(ISD::CondCode Opcode) {
237 default: assert(0 && "Illegal integer setcc operation!");
239 case ISD::SETNE: return 0;
243 case ISD::SETGE: return 1;
247 case ISD::SETUGE: return 2;
251 /// getSetCCOrOperation - Return the result of a logical OR between different
252 /// comparisons of identical values: ((X op1 Y) | (X op2 Y)). This function
253 /// returns SETCC_INVALID if it is not possible to represent the resultant
255 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
257 if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
258 // Cannot fold a signed integer setcc with an unsigned integer setcc.
259 return ISD::SETCC_INVALID;
261 unsigned Op = Op1 | Op2; // Combine all of the condition bits.
263 // If the N and U bits get set then the resultant comparison DOES suddenly
264 // care about orderedness, and is true when ordered.
265 if (Op > ISD::SETTRUE2)
266 Op &= ~16; // Clear the U bit if the N bit is set.
268 // Canonicalize illegal integer setcc's.
269 if (isInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT
272 return ISD::CondCode(Op);
275 /// getSetCCAndOperation - Return the result of a logical AND between different
276 /// comparisons of identical values: ((X op1 Y) & (X op2 Y)). This
277 /// function returns zero if it is not possible to represent the resultant
279 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
281 if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
282 // Cannot fold a signed setcc with an unsigned setcc.
283 return ISD::SETCC_INVALID;
285 // Combine all of the condition bits.
286 ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
288 // Canonicalize illegal integer setcc's.
292 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT
293 case ISD::SETOEQ: // SETEQ & SETU[LG]E
294 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE
295 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE
296 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE
303 const TargetMachine &SelectionDAG::getTarget() const {
304 return TLI.getTargetMachine();
307 //===----------------------------------------------------------------------===//
308 // SDNode Profile Support
309 //===----------------------------------------------------------------------===//
311 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
313 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) {
317 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
318 /// solely with their pointer.
319 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
320 ID.AddPointer(VTList.VTs);
323 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
325 static void AddNodeIDOperands(FoldingSetNodeID &ID,
326 const SDOperand *Ops, unsigned NumOps) {
327 for (; NumOps; --NumOps, ++Ops) {
328 ID.AddPointer(Ops->Val);
329 ID.AddInteger(Ops->ResNo);
333 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
335 static void AddNodeIDOperands(FoldingSetNodeID &ID,
336 const SDUse *Ops, unsigned NumOps) {
337 for (; NumOps; --NumOps, ++Ops) {
338 ID.AddPointer(Ops->getSDOperand().Val);
339 ID.AddInteger(Ops->getSDOperand().ResNo);
343 static void AddNodeIDNode(FoldingSetNodeID &ID,
344 unsigned short OpC, SDVTList VTList,
345 const SDOperand *OpList, unsigned N) {
346 AddNodeIDOpcode(ID, OpC);
347 AddNodeIDValueTypes(ID, VTList);
348 AddNodeIDOperands(ID, OpList, N);
352 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
354 static void AddNodeIDNode(FoldingSetNodeID &ID, SDNode *N) {
355 AddNodeIDOpcode(ID, N->getOpcode());
356 // Add the return value info.
357 AddNodeIDValueTypes(ID, N->getVTList());
358 // Add the operand info.
359 AddNodeIDOperands(ID, N->op_begin(), N->getNumOperands());
361 // Handle SDNode leafs with special info.
362 switch (N->getOpcode()) {
363 default: break; // Normal nodes don't need extra info.
365 ID.AddInteger(cast<ARG_FLAGSSDNode>(N)->getArgFlags().getRawBits());
367 case ISD::TargetConstant:
369 ID.Add(cast<ConstantSDNode>(N)->getAPIntValue());
371 case ISD::TargetConstantFP:
372 case ISD::ConstantFP: {
373 ID.Add(cast<ConstantFPSDNode>(N)->getValueAPF());
376 case ISD::TargetGlobalAddress:
377 case ISD::GlobalAddress:
378 case ISD::TargetGlobalTLSAddress:
379 case ISD::GlobalTLSAddress: {
380 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
381 ID.AddPointer(GA->getGlobal());
382 ID.AddInteger(GA->getOffset());
385 case ISD::BasicBlock:
386 ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
389 ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
391 case ISD::DBG_STOPPOINT: {
392 const DbgStopPointSDNode *DSP = cast<DbgStopPointSDNode>(N);
393 ID.AddInteger(DSP->getLine());
394 ID.AddInteger(DSP->getColumn());
395 ID.AddPointer(DSP->getCompileUnit());
400 ID.AddInteger(cast<LabelSDNode>(N)->getLabelID());
403 ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
405 case ISD::MEMOPERAND: {
406 const MachineMemOperand &MO = cast<MemOperandSDNode>(N)->MO;
407 ID.AddPointer(MO.getValue());
408 ID.AddInteger(MO.getFlags());
409 ID.AddInteger(MO.getOffset());
410 ID.AddInteger(MO.getSize());
411 ID.AddInteger(MO.getAlignment());
414 case ISD::FrameIndex:
415 case ISD::TargetFrameIndex:
416 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
419 case ISD::TargetJumpTable:
420 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
422 case ISD::ConstantPool:
423 case ISD::TargetConstantPool: {
424 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
425 ID.AddInteger(CP->getAlignment());
426 ID.AddInteger(CP->getOffset());
427 if (CP->isMachineConstantPoolEntry())
428 CP->getMachineCPVal()->AddSelectionDAGCSEId(ID);
430 ID.AddPointer(CP->getConstVal());
434 LoadSDNode *LD = cast<LoadSDNode>(N);
435 ID.AddInteger(LD->getAddressingMode());
436 ID.AddInteger(LD->getExtensionType());
437 ID.AddInteger(LD->getMemoryVT().getRawBits());
438 ID.AddInteger(LD->getAlignment());
439 ID.AddInteger(LD->isVolatile());
443 StoreSDNode *ST = cast<StoreSDNode>(N);
444 ID.AddInteger(ST->getAddressingMode());
445 ID.AddInteger(ST->isTruncatingStore());
446 ID.AddInteger(ST->getMemoryVT().getRawBits());
447 ID.AddInteger(ST->getAlignment());
448 ID.AddInteger(ST->isVolatile());
451 case ISD::ATOMIC_CMP_SWAP:
452 case ISD::ATOMIC_LOAD_ADD:
453 case ISD::ATOMIC_SWAP:
454 case ISD::ATOMIC_LOAD_SUB:
455 case ISD::ATOMIC_LOAD_AND:
456 case ISD::ATOMIC_LOAD_OR:
457 case ISD::ATOMIC_LOAD_XOR:
458 case ISD::ATOMIC_LOAD_NAND:
459 case ISD::ATOMIC_LOAD_MIN:
460 case ISD::ATOMIC_LOAD_MAX:
461 case ISD::ATOMIC_LOAD_UMIN:
462 case ISD::ATOMIC_LOAD_UMAX: {
463 AtomicSDNode *AT = cast<AtomicSDNode>(N);
464 ID.AddInteger(AT->getAlignment());
465 ID.AddInteger(AT->isVolatile());
468 } // end switch (N->getOpcode())
471 //===----------------------------------------------------------------------===//
472 // SelectionDAG Class
473 //===----------------------------------------------------------------------===//
475 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
477 void SelectionDAG::RemoveDeadNodes() {
478 // Create a dummy node (which is not added to allnodes), that adds a reference
479 // to the root node, preventing it from being deleted.
480 HandleSDNode Dummy(getRoot());
482 SmallVector<SDNode*, 128> DeadNodes;
484 // Add all obviously-dead nodes to the DeadNodes worklist.
485 for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I)
487 DeadNodes.push_back(I);
489 RemoveDeadNodes(DeadNodes);
491 // If the root changed (e.g. it was a dead load, update the root).
492 setRoot(Dummy.getValue());
495 /// RemoveDeadNodes - This method deletes the unreachable nodes in the
496 /// given list, and any nodes that become unreachable as a result.
497 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes,
498 DAGUpdateListener *UpdateListener) {
500 // Process the worklist, deleting the nodes and adding their uses to the
502 while (!DeadNodes.empty()) {
503 SDNode *N = DeadNodes.back();
504 DeadNodes.pop_back();
507 UpdateListener->NodeDeleted(N, 0);
509 // Take the node out of the appropriate CSE map.
510 RemoveNodeFromCSEMaps(N);
512 // Next, brutally remove the operand list. This is safe to do, as there are
513 // no cycles in the graph.
514 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
515 SDNode *Operand = I->getVal();
516 Operand->removeUser(std::distance(N->op_begin(), I), N);
518 // Now that we removed this operand, see if there are no uses of it left.
519 if (Operand->use_empty())
520 DeadNodes.push_back(Operand);
522 if (N->OperandsNeedDelete) {
523 delete[] N->OperandList;
528 // Finally, remove N itself.
533 void SelectionDAG::RemoveDeadNode(SDNode *N, DAGUpdateListener *UpdateListener){
534 SmallVector<SDNode*, 16> DeadNodes;
535 DeadNodes.push_back(N);
536 RemoveDeadNodes(DeadNodes, UpdateListener);
539 void SelectionDAG::DeleteNode(SDNode *N) {
540 assert(N->use_empty() && "Cannot delete a node that is not dead!");
542 // First take this out of the appropriate CSE map.
543 RemoveNodeFromCSEMaps(N);
545 // Finally, remove uses due to operands of this node, remove from the
546 // AllNodes list, and delete the node.
547 DeleteNodeNotInCSEMaps(N);
550 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
552 // Remove it from the AllNodes list.
555 // Drop all of the operands and decrement used nodes use counts.
556 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I)
557 I->getVal()->removeUser(std::distance(N->op_begin(), I), N);
558 if (N->OperandsNeedDelete) {
559 delete[] N->OperandList;
567 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
568 /// correspond to it. This is useful when we're about to delete or repurpose
569 /// the node. We don't want future request for structurally identical nodes
570 /// to return N anymore.
571 void SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
573 switch (N->getOpcode()) {
574 case ISD::HANDLENODE: return; // noop.
576 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
577 "Cond code doesn't exist!");
578 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != 0;
579 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = 0;
581 case ISD::ExternalSymbol:
582 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
584 case ISD::TargetExternalSymbol:
586 TargetExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
588 case ISD::VALUETYPE: {
589 MVT VT = cast<VTSDNode>(N)->getVT();
590 if (VT.isExtended()) {
591 Erased = ExtendedValueTypeNodes.erase(VT);
593 Erased = ValueTypeNodes[VT.getSimpleVT()] != 0;
594 ValueTypeNodes[VT.getSimpleVT()] = 0;
599 // Remove it from the CSE Map.
600 Erased = CSEMap.RemoveNode(N);
604 // Verify that the node was actually in one of the CSE maps, unless it has a
605 // flag result (which cannot be CSE'd) or is one of the special cases that are
606 // not subject to CSE.
607 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Flag &&
608 !N->isTargetOpcode()) {
611 assert(0 && "Node is not in map!");
616 /// AddNonLeafNodeToCSEMaps - Add the specified node back to the CSE maps. It
617 /// has been taken out and modified in some way. If the specified node already
618 /// exists in the CSE maps, do not modify the maps, but return the existing node
619 /// instead. If it doesn't exist, add it and return null.
621 SDNode *SelectionDAG::AddNonLeafNodeToCSEMaps(SDNode *N) {
622 assert(N->getNumOperands() && "This is a leaf node!");
623 if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
624 return 0; // Never add these nodes.
626 // Check that remaining values produced are not flags.
627 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
628 if (N->getValueType(i) == MVT::Flag)
629 return 0; // Never CSE anything that produces a flag.
631 SDNode *New = CSEMap.GetOrInsertNode(N);
632 if (New != N) return New; // Node already existed.
636 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
637 /// were replaced with those specified. If this node is never memoized,
638 /// return null, otherwise return a pointer to the slot it would take. If a
639 /// node already exists with these operands, the slot will be non-null.
640 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDOperand Op,
642 if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
643 return 0; // Never add these nodes.
645 // Check that remaining values produced are not flags.
646 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
647 if (N->getValueType(i) == MVT::Flag)
648 return 0; // Never CSE anything that produces a flag.
650 SDOperand Ops[] = { Op };
652 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 1);
653 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
656 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
657 /// were replaced with those specified. If this node is never memoized,
658 /// return null, otherwise return a pointer to the slot it would take. If a
659 /// node already exists with these operands, the slot will be non-null.
660 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
661 SDOperand Op1, SDOperand Op2,
663 if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
664 return 0; // Never add these nodes.
666 // Check that remaining values produced are not flags.
667 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
668 if (N->getValueType(i) == MVT::Flag)
669 return 0; // Never CSE anything that produces a flag.
671 SDOperand Ops[] = { Op1, Op2 };
673 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 2);
674 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
678 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
679 /// were replaced with those specified. If this node is never memoized,
680 /// return null, otherwise return a pointer to the slot it would take. If a
681 /// node already exists with these operands, the slot will be non-null.
682 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
683 const SDOperand *Ops,unsigned NumOps,
685 if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
686 return 0; // Never add these nodes.
688 // Check that remaining values produced are not flags.
689 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
690 if (N->getValueType(i) == MVT::Flag)
691 return 0; // Never CSE anything that produces a flag.
694 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, NumOps);
696 if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
697 ID.AddInteger(LD->getAddressingMode());
698 ID.AddInteger(LD->getExtensionType());
699 ID.AddInteger(LD->getMemoryVT().getRawBits());
700 ID.AddInteger(LD->getAlignment());
701 ID.AddInteger(LD->isVolatile());
702 } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
703 ID.AddInteger(ST->getAddressingMode());
704 ID.AddInteger(ST->isTruncatingStore());
705 ID.AddInteger(ST->getMemoryVT().getRawBits());
706 ID.AddInteger(ST->getAlignment());
707 ID.AddInteger(ST->isVolatile());
710 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
714 SelectionDAG::~SelectionDAG() {
715 while (!AllNodes.empty()) {
716 SDNode *N = AllNodes.begin();
717 N->SetNextInBucket(0);
718 if (N->OperandsNeedDelete) {
719 delete [] N->OperandList;
723 AllNodes.pop_front();
727 SDOperand SelectionDAG::getZeroExtendInReg(SDOperand Op, MVT VT) {
728 if (Op.getValueType() == VT) return Op;
729 APInt Imm = APInt::getLowBitsSet(Op.getValueSizeInBits(),
731 return getNode(ISD::AND, Op.getValueType(), Op,
732 getConstant(Imm, Op.getValueType()));
735 SDOperand SelectionDAG::getConstant(uint64_t Val, MVT VT, bool isT) {
736 MVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
737 return getConstant(APInt(EltVT.getSizeInBits(), Val), VT, isT);
740 SDOperand SelectionDAG::getConstant(const APInt &Val, MVT VT, bool isT) {
741 assert(VT.isInteger() && "Cannot create FP integer constant!");
743 MVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
744 assert(Val.getBitWidth() == EltVT.getSizeInBits() &&
745 "APInt size does not match type size!");
747 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
749 AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0);
753 if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
755 return SDOperand(N, 0);
757 N = new ConstantSDNode(isT, Val, EltVT);
758 CSEMap.InsertNode(N, IP);
759 AllNodes.push_back(N);
762 SDOperand Result(N, 0);
764 SmallVector<SDOperand, 8> Ops;
765 Ops.assign(VT.getVectorNumElements(), Result);
766 Result = getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
771 SDOperand SelectionDAG::getIntPtrConstant(uint64_t Val, bool isTarget) {
772 return getConstant(Val, TLI.getPointerTy(), isTarget);
776 SDOperand SelectionDAG::getConstantFP(const APFloat& V, MVT VT, bool isTarget) {
777 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
780 VT.isVector() ? VT.getVectorElementType() : VT;
782 // Do the map lookup using the actual bit pattern for the floating point
783 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
784 // we don't have issues with SNANs.
785 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
787 AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0);
791 if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
793 return SDOperand(N, 0);
795 N = new ConstantFPSDNode(isTarget, V, EltVT);
796 CSEMap.InsertNode(N, IP);
797 AllNodes.push_back(N);
800 SDOperand Result(N, 0);
802 SmallVector<SDOperand, 8> Ops;
803 Ops.assign(VT.getVectorNumElements(), Result);
804 Result = getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
809 SDOperand SelectionDAG::getConstantFP(double Val, MVT VT, bool isTarget) {
811 VT.isVector() ? VT.getVectorElementType() : VT;
813 return getConstantFP(APFloat((float)Val), VT, isTarget);
815 return getConstantFP(APFloat(Val), VT, isTarget);
818 SDOperand SelectionDAG::getGlobalAddress(const GlobalValue *GV,
823 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
825 // If GV is an alias then use the aliasee for determining thread-localness.
826 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
827 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal());
830 if (GVar && GVar->isThreadLocal())
831 Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
833 Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
836 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
838 ID.AddInteger(Offset);
840 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
841 return SDOperand(E, 0);
842 SDNode *N = new GlobalAddressSDNode(isTargetGA, GV, VT, Offset);
843 CSEMap.InsertNode(N, IP);
844 AllNodes.push_back(N);
845 return SDOperand(N, 0);
848 SDOperand SelectionDAG::getFrameIndex(int FI, MVT VT, bool isTarget) {
849 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
851 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
854 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
855 return SDOperand(E, 0);
856 SDNode *N = new FrameIndexSDNode(FI, VT, isTarget);
857 CSEMap.InsertNode(N, IP);
858 AllNodes.push_back(N);
859 return SDOperand(N, 0);
862 SDOperand SelectionDAG::getJumpTable(int JTI, MVT VT, bool isTarget){
863 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
865 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
868 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
869 return SDOperand(E, 0);
870 SDNode *N = new JumpTableSDNode(JTI, VT, isTarget);
871 CSEMap.InsertNode(N, IP);
872 AllNodes.push_back(N);
873 return SDOperand(N, 0);
876 SDOperand SelectionDAG::getConstantPool(Constant *C, MVT VT,
877 unsigned Alignment, int Offset,
879 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
881 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
882 ID.AddInteger(Alignment);
883 ID.AddInteger(Offset);
886 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
887 return SDOperand(E, 0);
888 SDNode *N = new ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment);
889 CSEMap.InsertNode(N, IP);
890 AllNodes.push_back(N);
891 return SDOperand(N, 0);
895 SDOperand SelectionDAG::getConstantPool(MachineConstantPoolValue *C, MVT VT,
896 unsigned Alignment, int Offset,
898 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
900 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
901 ID.AddInteger(Alignment);
902 ID.AddInteger(Offset);
903 C->AddSelectionDAGCSEId(ID);
905 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
906 return SDOperand(E, 0);
907 SDNode *N = new ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment);
908 CSEMap.InsertNode(N, IP);
909 AllNodes.push_back(N);
910 return SDOperand(N, 0);
914 SDOperand SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
916 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), 0, 0);
919 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
920 return SDOperand(E, 0);
921 SDNode *N = new BasicBlockSDNode(MBB);
922 CSEMap.InsertNode(N, IP);
923 AllNodes.push_back(N);
924 return SDOperand(N, 0);
927 SDOperand SelectionDAG::getArgFlags(ISD::ArgFlagsTy Flags) {
929 AddNodeIDNode(ID, ISD::ARG_FLAGS, getVTList(MVT::Other), 0, 0);
930 ID.AddInteger(Flags.getRawBits());
932 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
933 return SDOperand(E, 0);
934 SDNode *N = new ARG_FLAGSSDNode(Flags);
935 CSEMap.InsertNode(N, IP);
936 AllNodes.push_back(N);
937 return SDOperand(N, 0);
940 SDOperand SelectionDAG::getValueType(MVT VT) {
941 if (VT.isSimple() && (unsigned)VT.getSimpleVT() >= ValueTypeNodes.size())
942 ValueTypeNodes.resize(VT.getSimpleVT()+1);
944 SDNode *&N = VT.isExtended() ?
945 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT()];
947 if (N) return SDOperand(N, 0);
948 N = new VTSDNode(VT);
949 AllNodes.push_back(N);
950 return SDOperand(N, 0);
953 SDOperand SelectionDAG::getExternalSymbol(const char *Sym, MVT VT) {
954 SDNode *&N = ExternalSymbols[Sym];
955 if (N) return SDOperand(N, 0);
956 N = new ExternalSymbolSDNode(false, Sym, VT);
957 AllNodes.push_back(N);
958 return SDOperand(N, 0);
961 SDOperand SelectionDAG::getTargetExternalSymbol(const char *Sym, MVT VT) {
962 SDNode *&N = TargetExternalSymbols[Sym];
963 if (N) return SDOperand(N, 0);
964 N = new ExternalSymbolSDNode(true, Sym, VT);
965 AllNodes.push_back(N);
966 return SDOperand(N, 0);
969 SDOperand SelectionDAG::getCondCode(ISD::CondCode Cond) {
970 if ((unsigned)Cond >= CondCodeNodes.size())
971 CondCodeNodes.resize(Cond+1);
973 if (CondCodeNodes[Cond] == 0) {
974 CondCodeNodes[Cond] = new CondCodeSDNode(Cond);
975 AllNodes.push_back(CondCodeNodes[Cond]);
977 return SDOperand(CondCodeNodes[Cond], 0);
980 SDOperand SelectionDAG::getRegister(unsigned RegNo, MVT VT) {
982 AddNodeIDNode(ID, ISD::Register, getVTList(VT), 0, 0);
983 ID.AddInteger(RegNo);
985 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
986 return SDOperand(E, 0);
987 SDNode *N = new RegisterSDNode(RegNo, VT);
988 CSEMap.InsertNode(N, IP);
989 AllNodes.push_back(N);
990 return SDOperand(N, 0);
993 SDOperand SelectionDAG::getDbgStopPoint(SDOperand Root,
994 unsigned Line, unsigned Col,
995 const CompileUnitDesc *CU) {
997 SDOperand Ops[] = { Root };
998 AddNodeIDNode(ID, ISD::DBG_STOPPOINT, getVTList(MVT::Other), &Ops[0], 1);
1003 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1004 return SDOperand(E, 0);
1005 SDNode *N = new DbgStopPointSDNode(Root, Line, Col, CU);
1006 CSEMap.InsertNode(N, IP);
1007 AllNodes.push_back(N);
1008 return SDOperand(N, 0);
1011 SDOperand SelectionDAG::getLabel(unsigned Opcode,
1014 FoldingSetNodeID ID;
1015 SDOperand Ops[] = { Root };
1016 AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), &Ops[0], 1);
1017 ID.AddInteger(LabelID);
1019 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1020 return SDOperand(E, 0);
1021 SDNode *N = new LabelSDNode(Opcode, Root, LabelID);
1022 CSEMap.InsertNode(N, IP);
1023 AllNodes.push_back(N);
1024 return SDOperand(N, 0);
1027 SDOperand SelectionDAG::getSrcValue(const Value *V) {
1028 assert((!V || isa<PointerType>(V->getType())) &&
1029 "SrcValue is not a pointer?");
1031 FoldingSetNodeID ID;
1032 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), 0, 0);
1036 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1037 return SDOperand(E, 0);
1039 SDNode *N = new SrcValueSDNode(V);
1040 CSEMap.InsertNode(N, IP);
1041 AllNodes.push_back(N);
1042 return SDOperand(N, 0);
1045 SDOperand SelectionDAG::getMemOperand(const MachineMemOperand &MO) {
1046 const Value *v = MO.getValue();
1047 assert((!v || isa<PointerType>(v->getType())) &&
1048 "SrcValue is not a pointer?");
1050 FoldingSetNodeID ID;
1051 AddNodeIDNode(ID, ISD::MEMOPERAND, getVTList(MVT::Other), 0, 0);
1053 ID.AddInteger(MO.getFlags());
1054 ID.AddInteger(MO.getOffset());
1055 ID.AddInteger(MO.getSize());
1056 ID.AddInteger(MO.getAlignment());
1059 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1060 return SDOperand(E, 0);
1062 SDNode *N = new MemOperandSDNode(MO);
1063 CSEMap.InsertNode(N, IP);
1064 AllNodes.push_back(N);
1065 return SDOperand(N, 0);
1068 /// CreateStackTemporary - Create a stack temporary, suitable for holding the
1069 /// specified value type.
1070 SDOperand SelectionDAG::CreateStackTemporary(MVT VT, unsigned minAlign) {
1071 MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo();
1072 unsigned ByteSize = VT.getSizeInBits()/8;
1073 const Type *Ty = VT.getTypeForMVT();
1074 unsigned StackAlign =
1075 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty), minAlign);
1077 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign);
1078 return getFrameIndex(FrameIdx, TLI.getPointerTy());
1081 SDOperand SelectionDAG::FoldSetCC(MVT VT, SDOperand N1,
1082 SDOperand N2, ISD::CondCode Cond) {
1083 // These setcc operations always fold.
1087 case ISD::SETFALSE2: return getConstant(0, VT);
1089 case ISD::SETTRUE2: return getConstant(1, VT);
1101 assert(!N1.getValueType().isInteger() && "Illegal setcc for integer!");
1105 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val)) {
1106 const APInt &C2 = N2C->getAPIntValue();
1107 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val)) {
1108 const APInt &C1 = N1C->getAPIntValue();
1111 default: assert(0 && "Unknown integer setcc!");
1112 case ISD::SETEQ: return getConstant(C1 == C2, VT);
1113 case ISD::SETNE: return getConstant(C1 != C2, VT);
1114 case ISD::SETULT: return getConstant(C1.ult(C2), VT);
1115 case ISD::SETUGT: return getConstant(C1.ugt(C2), VT);
1116 case ISD::SETULE: return getConstant(C1.ule(C2), VT);
1117 case ISD::SETUGE: return getConstant(C1.uge(C2), VT);
1118 case ISD::SETLT: return getConstant(C1.slt(C2), VT);
1119 case ISD::SETGT: return getConstant(C1.sgt(C2), VT);
1120 case ISD::SETLE: return getConstant(C1.sle(C2), VT);
1121 case ISD::SETGE: return getConstant(C1.sge(C2), VT);
1125 if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1.Val)) {
1126 if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2.Val)) {
1127 // No compile time operations on this type yet.
1128 if (N1C->getValueType(0) == MVT::ppcf128)
1131 APFloat::cmpResult R = N1C->getValueAPF().compare(N2C->getValueAPF());
1134 case ISD::SETEQ: if (R==APFloat::cmpUnordered)
1135 return getNode(ISD::UNDEF, VT);
1137 case ISD::SETOEQ: return getConstant(R==APFloat::cmpEqual, VT);
1138 case ISD::SETNE: if (R==APFloat::cmpUnordered)
1139 return getNode(ISD::UNDEF, VT);
1141 case ISD::SETONE: return getConstant(R==APFloat::cmpGreaterThan ||
1142 R==APFloat::cmpLessThan, VT);
1143 case ISD::SETLT: if (R==APFloat::cmpUnordered)
1144 return getNode(ISD::UNDEF, VT);
1146 case ISD::SETOLT: return getConstant(R==APFloat::cmpLessThan, VT);
1147 case ISD::SETGT: if (R==APFloat::cmpUnordered)
1148 return getNode(ISD::UNDEF, VT);
1150 case ISD::SETOGT: return getConstant(R==APFloat::cmpGreaterThan, VT);
1151 case ISD::SETLE: if (R==APFloat::cmpUnordered)
1152 return getNode(ISD::UNDEF, VT);
1154 case ISD::SETOLE: return getConstant(R==APFloat::cmpLessThan ||
1155 R==APFloat::cmpEqual, VT);
1156 case ISD::SETGE: if (R==APFloat::cmpUnordered)
1157 return getNode(ISD::UNDEF, VT);
1159 case ISD::SETOGE: return getConstant(R==APFloat::cmpGreaterThan ||
1160 R==APFloat::cmpEqual, VT);
1161 case ISD::SETO: return getConstant(R!=APFloat::cmpUnordered, VT);
1162 case ISD::SETUO: return getConstant(R==APFloat::cmpUnordered, VT);
1163 case ISD::SETUEQ: return getConstant(R==APFloat::cmpUnordered ||
1164 R==APFloat::cmpEqual, VT);
1165 case ISD::SETUNE: return getConstant(R!=APFloat::cmpEqual, VT);
1166 case ISD::SETULT: return getConstant(R==APFloat::cmpUnordered ||
1167 R==APFloat::cmpLessThan, VT);
1168 case ISD::SETUGT: return getConstant(R==APFloat::cmpGreaterThan ||
1169 R==APFloat::cmpUnordered, VT);
1170 case ISD::SETULE: return getConstant(R!=APFloat::cmpGreaterThan, VT);
1171 case ISD::SETUGE: return getConstant(R!=APFloat::cmpLessThan, VT);
1174 // Ensure that the constant occurs on the RHS.
1175 return getSetCC(VT, N2, N1, ISD::getSetCCSwappedOperands(Cond));
1179 // Could not fold it.
1183 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We
1184 /// use this predicate to simplify operations downstream.
1185 bool SelectionDAG::SignBitIsZero(SDOperand Op, unsigned Depth) const {
1186 unsigned BitWidth = Op.getValueSizeInBits();
1187 return MaskedValueIsZero(Op, APInt::getSignBit(BitWidth), Depth);
1190 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1191 /// this predicate to simplify operations downstream. Mask is known to be zero
1192 /// for bits that V cannot have.
1193 bool SelectionDAG::MaskedValueIsZero(SDOperand Op, const APInt &Mask,
1194 unsigned Depth) const {
1195 APInt KnownZero, KnownOne;
1196 ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
1197 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1198 return (KnownZero & Mask) == Mask;
1201 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
1202 /// known to be either zero or one and return them in the KnownZero/KnownOne
1203 /// bitsets. This code only analyzes bits in Mask, in order to short-circuit
1205 void SelectionDAG::ComputeMaskedBits(SDOperand Op, const APInt &Mask,
1206 APInt &KnownZero, APInt &KnownOne,
1207 unsigned Depth) const {
1208 unsigned BitWidth = Mask.getBitWidth();
1209 assert(BitWidth == Op.getValueType().getSizeInBits() &&
1210 "Mask size mismatches value type size!");
1212 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
1213 if (Depth == 6 || Mask == 0)
1214 return; // Limit search depth.
1216 APInt KnownZero2, KnownOne2;
1218 switch (Op.getOpcode()) {
1220 // We know all of the bits for a constant!
1221 KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue() & Mask;
1222 KnownZero = ~KnownOne & Mask;
1225 // If either the LHS or the RHS are Zero, the result is zero.
1226 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1227 ComputeMaskedBits(Op.getOperand(0), Mask & ~KnownZero,
1228 KnownZero2, KnownOne2, Depth+1);
1229 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1230 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1232 // Output known-1 bits are only known if set in both the LHS & RHS.
1233 KnownOne &= KnownOne2;
1234 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1235 KnownZero |= KnownZero2;
1238 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1239 ComputeMaskedBits(Op.getOperand(0), Mask & ~KnownOne,
1240 KnownZero2, KnownOne2, Depth+1);
1241 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1242 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1244 // Output known-0 bits are only known if clear in both the LHS & RHS.
1245 KnownZero &= KnownZero2;
1246 // Output known-1 are known to be set if set in either the LHS | RHS.
1247 KnownOne |= KnownOne2;
1250 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1251 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
1252 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1253 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1255 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1256 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
1257 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1258 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
1259 KnownZero = KnownZeroOut;
1263 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
1264 ComputeMaskedBits(Op.getOperand(1), Mask2, KnownZero, KnownOne, Depth+1);
1265 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
1266 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1267 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1269 // If low bits are zero in either operand, output low known-0 bits.
1270 // Also compute a conserative estimate for high known-0 bits.
1271 // More trickiness is possible, but this is sufficient for the
1272 // interesting case of alignment computation.
1274 unsigned TrailZ = KnownZero.countTrailingOnes() +
1275 KnownZero2.countTrailingOnes();
1276 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
1277 KnownZero2.countLeadingOnes(),
1278 BitWidth) - BitWidth;
1280 TrailZ = std::min(TrailZ, BitWidth);
1281 LeadZ = std::min(LeadZ, BitWidth);
1282 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
1283 APInt::getHighBitsSet(BitWidth, LeadZ);
1288 // For the purposes of computing leading zeros we can conservatively
1289 // treat a udiv as a logical right shift by the power of 2 known to
1290 // be less than the denominator.
1291 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1292 ComputeMaskedBits(Op.getOperand(0),
1293 AllOnes, KnownZero2, KnownOne2, Depth+1);
1294 unsigned LeadZ = KnownZero2.countLeadingOnes();
1298 ComputeMaskedBits(Op.getOperand(1),
1299 AllOnes, KnownZero2, KnownOne2, Depth+1);
1300 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
1301 if (RHSUnknownLeadingOnes != BitWidth)
1302 LeadZ = std::min(BitWidth,
1303 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
1305 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
1309 ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
1310 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
1311 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1312 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1314 // Only known if known in both the LHS and RHS.
1315 KnownOne &= KnownOne2;
1316 KnownZero &= KnownZero2;
1318 case ISD::SELECT_CC:
1319 ComputeMaskedBits(Op.getOperand(3), Mask, KnownZero, KnownOne, Depth+1);
1320 ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero2, KnownOne2, Depth+1);
1321 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1322 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1324 // Only known if known in both the LHS and RHS.
1325 KnownOne &= KnownOne2;
1326 KnownZero &= KnownZero2;
1329 // If we know the result of a setcc has the top bits zero, use this info.
1330 if (TLI.getSetCCResultContents() == TargetLowering::ZeroOrOneSetCCResult &&
1332 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
1335 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
1336 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1337 unsigned ShAmt = SA->getValue();
1339 // If the shift count is an invalid immediate, don't do anything.
1340 if (ShAmt >= BitWidth)
1343 ComputeMaskedBits(Op.getOperand(0), Mask.lshr(ShAmt),
1344 KnownZero, KnownOne, Depth+1);
1345 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1346 KnownZero <<= ShAmt;
1348 // low bits known zero.
1349 KnownZero |= APInt::getLowBitsSet(BitWidth, ShAmt);
1353 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
1354 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1355 unsigned ShAmt = SA->getValue();
1357 // If the shift count is an invalid immediate, don't do anything.
1358 if (ShAmt >= BitWidth)
1361 ComputeMaskedBits(Op.getOperand(0), (Mask << ShAmt),
1362 KnownZero, KnownOne, Depth+1);
1363 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1364 KnownZero = KnownZero.lshr(ShAmt);
1365 KnownOne = KnownOne.lshr(ShAmt);
1367 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt) & Mask;
1368 KnownZero |= HighBits; // High bits known zero.
1372 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1373 unsigned ShAmt = SA->getValue();
1375 // If the shift count is an invalid immediate, don't do anything.
1376 if (ShAmt >= BitWidth)
1379 APInt InDemandedMask = (Mask << ShAmt);
1380 // If any of the demanded bits are produced by the sign extension, we also
1381 // demand the input sign bit.
1382 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt) & Mask;
1383 if (HighBits.getBoolValue())
1384 InDemandedMask |= APInt::getSignBit(BitWidth);
1386 ComputeMaskedBits(Op.getOperand(0), InDemandedMask, KnownZero, KnownOne,
1388 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1389 KnownZero = KnownZero.lshr(ShAmt);
1390 KnownOne = KnownOne.lshr(ShAmt);
1392 // Handle the sign bits.
1393 APInt SignBit = APInt::getSignBit(BitWidth);
1394 SignBit = SignBit.lshr(ShAmt); // Adjust to where it is now in the mask.
1396 if (KnownZero.intersects(SignBit)) {
1397 KnownZero |= HighBits; // New bits are known zero.
1398 } else if (KnownOne.intersects(SignBit)) {
1399 KnownOne |= HighBits; // New bits are known one.
1403 case ISD::SIGN_EXTEND_INREG: {
1404 MVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1405 unsigned EBits = EVT.getSizeInBits();
1407 // Sign extension. Compute the demanded bits in the result that are not
1408 // present in the input.
1409 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - EBits) & Mask;
1411 APInt InSignBit = APInt::getSignBit(EBits);
1412 APInt InputDemandedBits = Mask & APInt::getLowBitsSet(BitWidth, EBits);
1414 // If the sign extended bits are demanded, we know that the sign
1416 InSignBit.zext(BitWidth);
1417 if (NewBits.getBoolValue())
1418 InputDemandedBits |= InSignBit;
1420 ComputeMaskedBits(Op.getOperand(0), InputDemandedBits,
1421 KnownZero, KnownOne, Depth+1);
1422 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1424 // If the sign bit of the input is known set or clear, then we know the
1425 // top bits of the result.
1426 if (KnownZero.intersects(InSignBit)) { // Input sign bit known clear
1427 KnownZero |= NewBits;
1428 KnownOne &= ~NewBits;
1429 } else if (KnownOne.intersects(InSignBit)) { // Input sign bit known set
1430 KnownOne |= NewBits;
1431 KnownZero &= ~NewBits;
1432 } else { // Input sign bit unknown
1433 KnownZero &= ~NewBits;
1434 KnownOne &= ~NewBits;
1441 unsigned LowBits = Log2_32(BitWidth)+1;
1442 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1447 if (ISD::isZEXTLoad(Op.Val)) {
1448 LoadSDNode *LD = cast<LoadSDNode>(Op);
1449 MVT VT = LD->getMemoryVT();
1450 unsigned MemBits = VT.getSizeInBits();
1451 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits) & Mask;
1455 case ISD::ZERO_EXTEND: {
1456 MVT InVT = Op.getOperand(0).getValueType();
1457 unsigned InBits = InVT.getSizeInBits();
1458 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits) & Mask;
1459 APInt InMask = Mask;
1460 InMask.trunc(InBits);
1461 KnownZero.trunc(InBits);
1462 KnownOne.trunc(InBits);
1463 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1464 KnownZero.zext(BitWidth);
1465 KnownOne.zext(BitWidth);
1466 KnownZero |= NewBits;
1469 case ISD::SIGN_EXTEND: {
1470 MVT InVT = Op.getOperand(0).getValueType();
1471 unsigned InBits = InVT.getSizeInBits();
1472 APInt InSignBit = APInt::getSignBit(InBits);
1473 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits) & Mask;
1474 APInt InMask = Mask;
1475 InMask.trunc(InBits);
1477 // If any of the sign extended bits are demanded, we know that the sign
1478 // bit is demanded. Temporarily set this bit in the mask for our callee.
1479 if (NewBits.getBoolValue())
1480 InMask |= InSignBit;
1482 KnownZero.trunc(InBits);
1483 KnownOne.trunc(InBits);
1484 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1486 // Note if the sign bit is known to be zero or one.
1487 bool SignBitKnownZero = KnownZero.isNegative();
1488 bool SignBitKnownOne = KnownOne.isNegative();
1489 assert(!(SignBitKnownZero && SignBitKnownOne) &&
1490 "Sign bit can't be known to be both zero and one!");
1492 // If the sign bit wasn't actually demanded by our caller, we don't
1493 // want it set in the KnownZero and KnownOne result values. Reset the
1494 // mask and reapply it to the result values.
1496 InMask.trunc(InBits);
1497 KnownZero &= InMask;
1500 KnownZero.zext(BitWidth);
1501 KnownOne.zext(BitWidth);
1503 // If the sign bit is known zero or one, the top bits match.
1504 if (SignBitKnownZero)
1505 KnownZero |= NewBits;
1506 else if (SignBitKnownOne)
1507 KnownOne |= NewBits;
1510 case ISD::ANY_EXTEND: {
1511 MVT InVT = Op.getOperand(0).getValueType();
1512 unsigned InBits = InVT.getSizeInBits();
1513 APInt InMask = Mask;
1514 InMask.trunc(InBits);
1515 KnownZero.trunc(InBits);
1516 KnownOne.trunc(InBits);
1517 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1518 KnownZero.zext(BitWidth);
1519 KnownOne.zext(BitWidth);
1522 case ISD::TRUNCATE: {
1523 MVT InVT = Op.getOperand(0).getValueType();
1524 unsigned InBits = InVT.getSizeInBits();
1525 APInt InMask = Mask;
1526 InMask.zext(InBits);
1527 KnownZero.zext(InBits);
1528 KnownOne.zext(InBits);
1529 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1530 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1531 KnownZero.trunc(BitWidth);
1532 KnownOne.trunc(BitWidth);
1535 case ISD::AssertZext: {
1536 MVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1537 APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
1538 ComputeMaskedBits(Op.getOperand(0), Mask & InMask, KnownZero,
1540 KnownZero |= (~InMask) & Mask;
1544 // All bits are zero except the low bit.
1545 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - 1);
1549 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0))) {
1550 // We know that the top bits of C-X are clear if X contains less bits
1551 // than C (i.e. no wrap-around can happen). For example, 20-X is
1552 // positive if we can prove that X is >= 0 and < 16.
1553 if (CLHS->getAPIntValue().isNonNegative()) {
1554 unsigned NLZ = (CLHS->getAPIntValue()+1).countLeadingZeros();
1555 // NLZ can't be BitWidth with no sign bit
1556 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
1557 ComputeMaskedBits(Op.getOperand(1), MaskV, KnownZero2, KnownOne2,
1560 // If all of the MaskV bits are known to be zero, then we know the
1561 // output top bits are zero, because we now know that the output is
1563 if ((KnownZero2 & MaskV) == MaskV) {
1564 unsigned NLZ2 = CLHS->getAPIntValue().countLeadingZeros();
1565 // Top bits known zero.
1566 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
1573 // Output known-0 bits are known if clear or set in both the low clear bits
1574 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
1575 // low 3 bits clear.
1576 APInt Mask2 = APInt::getLowBitsSet(BitWidth, Mask.countTrailingOnes());
1577 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
1578 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1579 unsigned KnownZeroOut = KnownZero2.countTrailingOnes();
1581 ComputeMaskedBits(Op.getOperand(1), Mask2, KnownZero2, KnownOne2, Depth+1);
1582 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1583 KnownZeroOut = std::min(KnownZeroOut,
1584 KnownZero2.countTrailingOnes());
1586 KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroOut);
1590 if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1591 const APInt &RA = Rem->getAPIntValue();
1592 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
1593 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
1594 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1595 ComputeMaskedBits(Op.getOperand(0), Mask2,KnownZero2,KnownOne2,Depth+1);
1597 // The sign of a remainder is equal to the sign of the first
1598 // operand (zero being positive).
1599 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
1600 KnownZero2 |= ~LowBits;
1601 else if (KnownOne2[BitWidth-1])
1602 KnownOne2 |= ~LowBits;
1604 KnownZero |= KnownZero2 & Mask;
1605 KnownOne |= KnownOne2 & Mask;
1607 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1612 if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1613 const APInt &RA = Rem->getAPIntValue();
1614 if (RA.isPowerOf2()) {
1615 APInt LowBits = (RA - 1);
1616 APInt Mask2 = LowBits & Mask;
1617 KnownZero |= ~LowBits & Mask;
1618 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero, KnownOne,Depth+1);
1619 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1624 // Since the result is less than or equal to either operand, any leading
1625 // zero bits in either operand must also exist in the result.
1626 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1627 ComputeMaskedBits(Op.getOperand(0), AllOnes, KnownZero, KnownOne,
1629 ComputeMaskedBits(Op.getOperand(1), AllOnes, KnownZero2, KnownOne2,
1632 uint32_t Leaders = std::max(KnownZero.countLeadingOnes(),
1633 KnownZero2.countLeadingOnes());
1635 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
1639 // Allow the target to implement this method for its nodes.
1640 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) {
1641 case ISD::INTRINSIC_WO_CHAIN:
1642 case ISD::INTRINSIC_W_CHAIN:
1643 case ISD::INTRINSIC_VOID:
1644 TLI.computeMaskedBitsForTargetNode(Op, Mask, KnownZero, KnownOne, *this);
1650 /// ComputeNumSignBits - Return the number of times the sign bit of the
1651 /// register is replicated into the other bits. We know that at least 1 bit
1652 /// is always equal to the sign bit (itself), but other cases can give us
1653 /// information. For example, immediately after an "SRA X, 2", we know that
1654 /// the top 3 bits are all equal to each other, so we return 3.
1655 unsigned SelectionDAG::ComputeNumSignBits(SDOperand Op, unsigned Depth) const{
1656 MVT VT = Op.getValueType();
1657 assert(VT.isInteger() && "Invalid VT!");
1658 unsigned VTBits = VT.getSizeInBits();
1660 unsigned FirstAnswer = 1;
1663 return 1; // Limit search depth.
1665 switch (Op.getOpcode()) {
1667 case ISD::AssertSext:
1668 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
1669 return VTBits-Tmp+1;
1670 case ISD::AssertZext:
1671 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
1674 case ISD::Constant: {
1675 const APInt &Val = cast<ConstantSDNode>(Op)->getAPIntValue();
1676 // If negative, return # leading ones.
1677 if (Val.isNegative())
1678 return Val.countLeadingOnes();
1680 // Return # leading zeros.
1681 return Val.countLeadingZeros();
1684 case ISD::SIGN_EXTEND:
1685 Tmp = VTBits-Op.getOperand(0).getValueType().getSizeInBits();
1686 return ComputeNumSignBits(Op.getOperand(0), Depth+1) + Tmp;
1688 case ISD::SIGN_EXTEND_INREG:
1689 // Max of the input and what this extends.
1690 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
1693 Tmp2 = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1694 return std::max(Tmp, Tmp2);
1697 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1698 // SRA X, C -> adds C sign bits.
1699 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1700 Tmp += C->getValue();
1701 if (Tmp > VTBits) Tmp = VTBits;
1705 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1706 // shl destroys sign bits.
1707 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1708 if (C->getValue() >= VTBits || // Bad shift.
1709 C->getValue() >= Tmp) break; // Shifted all sign bits out.
1710 return Tmp - C->getValue();
1715 case ISD::XOR: // NOT is handled here.
1716 // Logical binary ops preserve the number of sign bits at the worst.
1717 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1719 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1720 FirstAnswer = std::min(Tmp, Tmp2);
1721 // We computed what we know about the sign bits as our first
1722 // answer. Now proceed to the generic code that uses
1723 // ComputeMaskedBits, and pick whichever answer is better.
1728 Tmp = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1729 if (Tmp == 1) return 1; // Early out.
1730 Tmp2 = ComputeNumSignBits(Op.getOperand(2), Depth+1);
1731 return std::min(Tmp, Tmp2);
1734 // If setcc returns 0/-1, all bits are sign bits.
1735 if (TLI.getSetCCResultContents() ==
1736 TargetLowering::ZeroOrNegativeOneSetCCResult)
1741 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1742 unsigned RotAmt = C->getValue() & (VTBits-1);
1744 // Handle rotate right by N like a rotate left by 32-N.
1745 if (Op.getOpcode() == ISD::ROTR)
1746 RotAmt = (VTBits-RotAmt) & (VTBits-1);
1748 // If we aren't rotating out all of the known-in sign bits, return the
1749 // number that are left. This handles rotl(sext(x), 1) for example.
1750 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1751 if (Tmp > RotAmt+1) return Tmp-RotAmt;
1755 // Add can have at most one carry bit. Thus we know that the output
1756 // is, at worst, one more bit than the inputs.
1757 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1758 if (Tmp == 1) return 1; // Early out.
1760 // Special case decrementing a value (ADD X, -1):
1761 if (ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
1762 if (CRHS->isAllOnesValue()) {
1763 APInt KnownZero, KnownOne;
1764 APInt Mask = APInt::getAllOnesValue(VTBits);
1765 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
1767 // If the input is known to be 0 or 1, the output is 0/-1, which is all
1769 if ((KnownZero | APInt(VTBits, 1)) == Mask)
1772 // If we are subtracting one from a positive number, there is no carry
1773 // out of the result.
1774 if (KnownZero.isNegative())
1778 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1779 if (Tmp2 == 1) return 1;
1780 return std::min(Tmp, Tmp2)-1;
1784 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1785 if (Tmp2 == 1) return 1;
1788 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
1789 if (CLHS->isNullValue()) {
1790 APInt KnownZero, KnownOne;
1791 APInt Mask = APInt::getAllOnesValue(VTBits);
1792 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1793 // If the input is known to be 0 or 1, the output is 0/-1, which is all
1795 if ((KnownZero | APInt(VTBits, 1)) == Mask)
1798 // If the input is known to be positive (the sign bit is known clear),
1799 // the output of the NEG has the same number of sign bits as the input.
1800 if (KnownZero.isNegative())
1803 // Otherwise, we treat this like a SUB.
1806 // Sub can have at most one carry bit. Thus we know that the output
1807 // is, at worst, one more bit than the inputs.
1808 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1809 if (Tmp == 1) return 1; // Early out.
1810 return std::min(Tmp, Tmp2)-1;
1813 // FIXME: it's tricky to do anything useful for this, but it is an important
1814 // case for targets like X86.
1818 // Handle LOADX separately here. EXTLOAD case will fallthrough.
1819 if (Op.getOpcode() == ISD::LOAD) {
1820 LoadSDNode *LD = cast<LoadSDNode>(Op);
1821 unsigned ExtType = LD->getExtensionType();
1824 case ISD::SEXTLOAD: // '17' bits known
1825 Tmp = LD->getMemoryVT().getSizeInBits();
1826 return VTBits-Tmp+1;
1827 case ISD::ZEXTLOAD: // '16' bits known
1828 Tmp = LD->getMemoryVT().getSizeInBits();
1833 // Allow the target to implement this method for its nodes.
1834 if (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
1835 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1836 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
1837 Op.getOpcode() == ISD::INTRINSIC_VOID) {
1838 unsigned NumBits = TLI.ComputeNumSignBitsForTargetNode(Op, Depth);
1839 if (NumBits > 1) FirstAnswer = std::max(FirstAnswer, NumBits);
1842 // Finally, if we can prove that the top bits of the result are 0's or 1's,
1843 // use this information.
1844 APInt KnownZero, KnownOne;
1845 APInt Mask = APInt::getAllOnesValue(VTBits);
1846 ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
1848 if (KnownZero.isNegative()) { // sign bit is 0
1850 } else if (KnownOne.isNegative()) { // sign bit is 1;
1857 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
1858 // the number of identical bits in the top of the input value.
1860 Mask <<= Mask.getBitWidth()-VTBits;
1861 // Return # leading zeros. We use 'min' here in case Val was zero before
1862 // shifting. We don't want to return '64' as for an i32 "0".
1863 return std::max(FirstAnswer, std::min(VTBits, Mask.countLeadingZeros()));
1867 bool SelectionDAG::isVerifiedDebugInfoDesc(SDOperand Op) const {
1868 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
1869 if (!GA) return false;
1870 GlobalVariable *GV = dyn_cast<GlobalVariable>(GA->getGlobal());
1871 if (!GV) return false;
1872 MachineModuleInfo *MMI = getMachineModuleInfo();
1873 return MMI && MMI->hasDebugInfo() && MMI->isVerified(GV);
1877 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
1878 /// element of the result of the vector shuffle.
1879 SDOperand SelectionDAG::getShuffleScalarElt(const SDNode *N, unsigned i) {
1880 MVT VT = N->getValueType(0);
1881 SDOperand PermMask = N->getOperand(2);
1882 SDOperand Idx = PermMask.getOperand(i);
1883 if (Idx.getOpcode() == ISD::UNDEF)
1884 return getNode(ISD::UNDEF, VT.getVectorElementType());
1885 unsigned Index = cast<ConstantSDNode>(Idx)->getValue();
1886 unsigned NumElems = PermMask.getNumOperands();
1887 SDOperand V = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
1890 if (V.getOpcode() == ISD::BIT_CONVERT) {
1891 V = V.getOperand(0);
1892 if (V.getValueType().getVectorNumElements() != NumElems)
1895 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
1896 return (Index == 0) ? V.getOperand(0)
1897 : getNode(ISD::UNDEF, VT.getVectorElementType());
1898 if (V.getOpcode() == ISD::BUILD_VECTOR)
1899 return V.getOperand(Index);
1900 if (V.getOpcode() == ISD::VECTOR_SHUFFLE)
1901 return getShuffleScalarElt(V.Val, Index);
1906 /// getNode - Gets or creates the specified node.
1908 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT) {
1909 FoldingSetNodeID ID;
1910 AddNodeIDNode(ID, Opcode, getVTList(VT), 0, 0);
1912 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1913 return SDOperand(E, 0);
1914 SDNode *N = new SDNode(Opcode, SDNode::getSDVTList(VT));
1915 CSEMap.InsertNode(N, IP);
1917 AllNodes.push_back(N);
1918 return SDOperand(N, 0);
1921 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT, SDOperand Operand) {
1922 // Constant fold unary operations with an integer constant operand.
1923 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand.Val)) {
1924 const APInt &Val = C->getAPIntValue();
1925 unsigned BitWidth = VT.getSizeInBits();
1928 case ISD::SIGN_EXTEND:
1929 return getConstant(APInt(Val).sextOrTrunc(BitWidth), VT);
1930 case ISD::ANY_EXTEND:
1931 case ISD::ZERO_EXTEND:
1933 return getConstant(APInt(Val).zextOrTrunc(BitWidth), VT);
1934 case ISD::UINT_TO_FP:
1935 case ISD::SINT_TO_FP: {
1936 const uint64_t zero[] = {0, 0};
1937 // No compile time operations on this type.
1938 if (VT==MVT::ppcf128)
1940 APFloat apf = APFloat(APInt(BitWidth, 2, zero));
1941 (void)apf.convertFromAPInt(Val,
1942 Opcode==ISD::SINT_TO_FP,
1943 APFloat::rmNearestTiesToEven);
1944 return getConstantFP(apf, VT);
1946 case ISD::BIT_CONVERT:
1947 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
1948 return getConstantFP(Val.bitsToFloat(), VT);
1949 else if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
1950 return getConstantFP(Val.bitsToDouble(), VT);
1953 return getConstant(Val.byteSwap(), VT);
1955 return getConstant(Val.countPopulation(), VT);
1957 return getConstant(Val.countLeadingZeros(), VT);
1959 return getConstant(Val.countTrailingZeros(), VT);
1963 // Constant fold unary operations with a floating point constant operand.
1964 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand.Val)) {
1965 APFloat V = C->getValueAPF(); // make copy
1966 if (VT != MVT::ppcf128 && Operand.getValueType() != MVT::ppcf128) {
1970 return getConstantFP(V, VT);
1973 return getConstantFP(V, VT);
1975 case ISD::FP_EXTEND:
1976 // This can return overflow, underflow, or inexact; we don't care.
1977 // FIXME need to be more flexible about rounding mode.
1978 (void)V.convert(*MVTToAPFloatSemantics(VT),
1979 APFloat::rmNearestTiesToEven);
1980 return getConstantFP(V, VT);
1981 case ISD::FP_TO_SINT:
1982 case ISD::FP_TO_UINT: {
1984 assert(integerPartWidth >= 64);
1985 // FIXME need to be more flexible about rounding mode.
1986 APFloat::opStatus s = V.convertToInteger(&x, 64U,
1987 Opcode==ISD::FP_TO_SINT,
1988 APFloat::rmTowardZero);
1989 if (s==APFloat::opInvalidOp) // inexact is OK, in fact usual
1991 return getConstant(x, VT);
1993 case ISD::BIT_CONVERT:
1994 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
1995 return getConstant((uint32_t)V.convertToAPInt().getZExtValue(), VT);
1996 else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
1997 return getConstant(V.convertToAPInt().getZExtValue(), VT);
2003 unsigned OpOpcode = Operand.Val->getOpcode();
2005 case ISD::TokenFactor:
2006 return Operand; // Factor of one node? No need.
2007 case ISD::FP_ROUND: assert(0 && "Invalid method to make FP_ROUND node");
2008 case ISD::FP_EXTEND:
2009 assert(VT.isFloatingPoint() &&
2010 Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
2011 if (Operand.getValueType() == VT) return Operand; // noop conversion.
2012 if (Operand.getOpcode() == ISD::UNDEF)
2013 return getNode(ISD::UNDEF, VT);
2015 case ISD::SIGN_EXTEND:
2016 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2017 "Invalid SIGN_EXTEND!");
2018 if (Operand.getValueType() == VT) return Operand; // noop extension
2019 assert(Operand.getValueType().bitsLT(VT)
2020 && "Invalid sext node, dst < src!");
2021 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
2022 return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
2024 case ISD::ZERO_EXTEND:
2025 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2026 "Invalid ZERO_EXTEND!");
2027 if (Operand.getValueType() == VT) return Operand; // noop extension
2028 assert(Operand.getValueType().bitsLT(VT)
2029 && "Invalid zext node, dst < src!");
2030 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x)
2031 return getNode(ISD::ZERO_EXTEND, VT, Operand.Val->getOperand(0));
2033 case ISD::ANY_EXTEND:
2034 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2035 "Invalid ANY_EXTEND!");
2036 if (Operand.getValueType() == VT) return Operand; // noop extension
2037 assert(Operand.getValueType().bitsLT(VT)
2038 && "Invalid anyext node, dst < src!");
2039 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND)
2040 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x)
2041 return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
2044 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2045 "Invalid TRUNCATE!");
2046 if (Operand.getValueType() == VT) return Operand; // noop truncate
2047 assert(Operand.getValueType().bitsGT(VT)
2048 && "Invalid truncate node, src < dst!");
2049 if (OpOpcode == ISD::TRUNCATE)
2050 return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
2051 else if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
2052 OpOpcode == ISD::ANY_EXTEND) {
2053 // If the source is smaller than the dest, we still need an extend.
2054 if (Operand.Val->getOperand(0).getValueType().bitsLT(VT))
2055 return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
2056 else if (Operand.Val->getOperand(0).getValueType().bitsGT(VT))
2057 return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
2059 return Operand.Val->getOperand(0);
2062 case ISD::BIT_CONVERT:
2063 // Basic sanity checking.
2064 assert(VT.getSizeInBits() == Operand.getValueType().getSizeInBits()
2065 && "Cannot BIT_CONVERT between types of different sizes!");
2066 if (VT == Operand.getValueType()) return Operand; // noop conversion.
2067 if (OpOpcode == ISD::BIT_CONVERT) // bitconv(bitconv(x)) -> bitconv(x)
2068 return getNode(ISD::BIT_CONVERT, VT, Operand.getOperand(0));
2069 if (OpOpcode == ISD::UNDEF)
2070 return getNode(ISD::UNDEF, VT);
2072 case ISD::SCALAR_TO_VECTOR:
2073 assert(VT.isVector() && !Operand.getValueType().isVector() &&
2074 VT.getVectorElementType() == Operand.getValueType() &&
2075 "Illegal SCALAR_TO_VECTOR node!");
2076 if (OpOpcode == ISD::UNDEF)
2077 return getNode(ISD::UNDEF, VT);
2078 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
2079 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
2080 isa<ConstantSDNode>(Operand.getOperand(1)) &&
2081 Operand.getConstantOperandVal(1) == 0 &&
2082 Operand.getOperand(0).getValueType() == VT)
2083 return Operand.getOperand(0);
2086 if (OpOpcode == ISD::FSUB) // -(X-Y) -> (Y-X)
2087 return getNode(ISD::FSUB, VT, Operand.Val->getOperand(1),
2088 Operand.Val->getOperand(0));
2089 if (OpOpcode == ISD::FNEG) // --X -> X
2090 return Operand.Val->getOperand(0);
2093 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X)
2094 return getNode(ISD::FABS, VT, Operand.Val->getOperand(0));
2099 SDVTList VTs = getVTList(VT);
2100 if (VT != MVT::Flag) { // Don't CSE flag producing nodes
2101 FoldingSetNodeID ID;
2102 SDOperand Ops[1] = { Operand };
2103 AddNodeIDNode(ID, Opcode, VTs, Ops, 1);
2105 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2106 return SDOperand(E, 0);
2107 N = new UnarySDNode(Opcode, VTs, Operand);
2108 CSEMap.InsertNode(N, IP);
2110 N = new UnarySDNode(Opcode, VTs, Operand);
2112 AllNodes.push_back(N);
2113 return SDOperand(N, 0);
2118 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
2119 SDOperand N1, SDOperand N2) {
2120 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
2121 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
2124 case ISD::TokenFactor:
2125 assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
2126 N2.getValueType() == MVT::Other && "Invalid token factor!");
2127 // Fold trivial token factors.
2128 if (N1.getOpcode() == ISD::EntryToken) return N2;
2129 if (N2.getOpcode() == ISD::EntryToken) return N1;
2132 assert(VT.isInteger() && N1.getValueType() == N2.getValueType() &&
2133 N1.getValueType() == VT && "Binary operator types must match!");
2134 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's
2135 // worth handling here.
2136 if (N2C && N2C->isNullValue())
2138 if (N2C && N2C->isAllOnesValue()) // X & -1 -> X
2145 assert(VT.isInteger() && N1.getValueType() == N2.getValueType() &&
2146 N1.getValueType() == VT && "Binary operator types must match!");
2147 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so
2148 // it's worth handling here.
2149 if (N2C && N2C->isNullValue())
2156 assert(VT.isInteger() && "This operator does not apply to FP types!");
2166 assert(N1.getValueType() == N2.getValueType() &&
2167 N1.getValueType() == VT && "Binary operator types must match!");
2169 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match.
2170 assert(N1.getValueType() == VT &&
2171 N1.getValueType().isFloatingPoint() &&
2172 N2.getValueType().isFloatingPoint() &&
2173 "Invalid FCOPYSIGN!");
2180 assert(VT == N1.getValueType() &&
2181 "Shift operators return type must be the same as their first arg");
2182 assert(VT.isInteger() && N2.getValueType().isInteger() &&
2183 "Shifts only work on integers");
2185 // Always fold shifts of i1 values so the code generator doesn't need to
2186 // handle them. Since we know the size of the shift has to be less than the
2187 // size of the value, the shift/rotate count is guaranteed to be zero.
2191 case ISD::FP_ROUND_INREG: {
2192 MVT EVT = cast<VTSDNode>(N2)->getVT();
2193 assert(VT == N1.getValueType() && "Not an inreg round!");
2194 assert(VT.isFloatingPoint() && EVT.isFloatingPoint() &&
2195 "Cannot FP_ROUND_INREG integer types");
2196 assert(EVT.bitsLE(VT) && "Not rounding down!");
2197 if (cast<VTSDNode>(N2)->getVT() == VT) return N1; // Not actually rounding.
2201 assert(VT.isFloatingPoint() &&
2202 N1.getValueType().isFloatingPoint() &&
2203 VT.bitsLE(N1.getValueType()) &&
2204 isa<ConstantSDNode>(N2) && "Invalid FP_ROUND!");
2205 if (N1.getValueType() == VT) return N1; // noop conversion.
2207 case ISD::AssertSext:
2208 case ISD::AssertZext: {
2209 MVT EVT = cast<VTSDNode>(N2)->getVT();
2210 assert(VT == N1.getValueType() && "Not an inreg extend!");
2211 assert(VT.isInteger() && EVT.isInteger() &&
2212 "Cannot *_EXTEND_INREG FP types");
2213 assert(EVT.bitsLE(VT) && "Not extending!");
2214 if (VT == EVT) return N1; // noop assertion.
2217 case ISD::SIGN_EXTEND_INREG: {
2218 MVT EVT = cast<VTSDNode>(N2)->getVT();
2219 assert(VT == N1.getValueType() && "Not an inreg extend!");
2220 assert(VT.isInteger() && EVT.isInteger() &&
2221 "Cannot *_EXTEND_INREG FP types");
2222 assert(EVT.bitsLE(VT) && "Not extending!");
2223 if (EVT == VT) return N1; // Not actually extending
2226 APInt Val = N1C->getAPIntValue();
2227 unsigned FromBits = cast<VTSDNode>(N2)->getVT().getSizeInBits();
2228 Val <<= Val.getBitWidth()-FromBits;
2229 Val = Val.ashr(Val.getBitWidth()-FromBits);
2230 return getConstant(Val, VT);
2234 case ISD::EXTRACT_VECTOR_ELT:
2235 assert(N2C && "Bad EXTRACT_VECTOR_ELT!");
2237 // EXTRACT_VECTOR_ELT of an UNDEF is an UNDEF.
2238 if (N1.getOpcode() == ISD::UNDEF)
2239 return getNode(ISD::UNDEF, VT);
2241 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
2242 // expanding copies of large vectors from registers.
2243 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
2244 N1.getNumOperands() > 0) {
2246 N1.getOperand(0).getValueType().getVectorNumElements();
2247 return getNode(ISD::EXTRACT_VECTOR_ELT, VT,
2248 N1.getOperand(N2C->getValue() / Factor),
2249 getConstant(N2C->getValue() % Factor, N2.getValueType()));
2252 // EXTRACT_VECTOR_ELT of BUILD_VECTOR is often formed while lowering is
2253 // expanding large vector constants.
2254 if (N1.getOpcode() == ISD::BUILD_VECTOR)
2255 return N1.getOperand(N2C->getValue());
2257 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
2258 // operations are lowered to scalars.
2259 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT)
2260 if (ConstantSDNode *IEC = dyn_cast<ConstantSDNode>(N1.getOperand(2))) {
2262 return N1.getOperand(1);
2264 return getNode(ISD::EXTRACT_VECTOR_ELT, VT, N1.getOperand(0), N2);
2267 case ISD::EXTRACT_ELEMENT:
2268 assert(N2C && (unsigned)N2C->getValue() < 2 && "Bad EXTRACT_ELEMENT!");
2269 assert(!N1.getValueType().isVector() && !VT.isVector() &&
2270 (N1.getValueType().isInteger() == VT.isInteger()) &&
2271 "Wrong types for EXTRACT_ELEMENT!");
2273 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
2274 // 64-bit integers into 32-bit parts. Instead of building the extract of
2275 // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
2276 if (N1.getOpcode() == ISD::BUILD_PAIR)
2277 return N1.getOperand(N2C->getValue());
2279 // EXTRACT_ELEMENT of a constant int is also very common.
2280 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2281 unsigned ElementSize = VT.getSizeInBits();
2282 unsigned Shift = ElementSize * N2C->getValue();
2283 APInt ShiftedVal = C->getAPIntValue().lshr(Shift);
2284 return getConstant(ShiftedVal.trunc(ElementSize), VT);
2287 case ISD::EXTRACT_SUBVECTOR:
2288 if (N1.getValueType() == VT) // Trivial extraction.
2295 const APInt &C1 = N1C->getAPIntValue(), &C2 = N2C->getAPIntValue();
2297 case ISD::ADD: return getConstant(C1 + C2, VT);
2298 case ISD::SUB: return getConstant(C1 - C2, VT);
2299 case ISD::MUL: return getConstant(C1 * C2, VT);
2301 if (C2.getBoolValue()) return getConstant(C1.udiv(C2), VT);
2304 if (C2.getBoolValue()) return getConstant(C1.urem(C2), VT);
2307 if (C2.getBoolValue()) return getConstant(C1.sdiv(C2), VT);
2310 if (C2.getBoolValue()) return getConstant(C1.srem(C2), VT);
2312 case ISD::AND : return getConstant(C1 & C2, VT);
2313 case ISD::OR : return getConstant(C1 | C2, VT);
2314 case ISD::XOR : return getConstant(C1 ^ C2, VT);
2315 case ISD::SHL : return getConstant(C1 << C2, VT);
2316 case ISD::SRL : return getConstant(C1.lshr(C2), VT);
2317 case ISD::SRA : return getConstant(C1.ashr(C2), VT);
2318 case ISD::ROTL : return getConstant(C1.rotl(C2), VT);
2319 case ISD::ROTR : return getConstant(C1.rotr(C2), VT);
2322 } else { // Cannonicalize constant to RHS if commutative
2323 if (isCommutativeBinOp(Opcode)) {
2324 std::swap(N1C, N2C);
2330 // Constant fold FP operations.
2331 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1.Val);
2332 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2.Val);
2334 if (!N2CFP && isCommutativeBinOp(Opcode)) {
2335 // Cannonicalize constant to RHS if commutative
2336 std::swap(N1CFP, N2CFP);
2338 } else if (N2CFP && VT != MVT::ppcf128) {
2339 APFloat V1 = N1CFP->getValueAPF(), V2 = N2CFP->getValueAPF();
2340 APFloat::opStatus s;
2343 s = V1.add(V2, APFloat::rmNearestTiesToEven);
2344 if (s != APFloat::opInvalidOp)
2345 return getConstantFP(V1, VT);
2348 s = V1.subtract(V2, APFloat::rmNearestTiesToEven);
2349 if (s!=APFloat::opInvalidOp)
2350 return getConstantFP(V1, VT);
2353 s = V1.multiply(V2, APFloat::rmNearestTiesToEven);
2354 if (s!=APFloat::opInvalidOp)
2355 return getConstantFP(V1, VT);
2358 s = V1.divide(V2, APFloat::rmNearestTiesToEven);
2359 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2360 return getConstantFP(V1, VT);
2363 s = V1.mod(V2, APFloat::rmNearestTiesToEven);
2364 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2365 return getConstantFP(V1, VT);
2367 case ISD::FCOPYSIGN:
2369 return getConstantFP(V1, VT);
2375 // Canonicalize an UNDEF to the RHS, even over a constant.
2376 if (N1.getOpcode() == ISD::UNDEF) {
2377 if (isCommutativeBinOp(Opcode)) {
2381 case ISD::FP_ROUND_INREG:
2382 case ISD::SIGN_EXTEND_INREG:
2388 return N1; // fold op(undef, arg2) -> undef
2396 return getConstant(0, VT); // fold op(undef, arg2) -> 0
2397 // For vectors, we can't easily build an all zero vector, just return
2404 // Fold a bunch of operators when the RHS is undef.
2405 if (N2.getOpcode() == ISD::UNDEF) {
2408 if (N1.getOpcode() == ISD::UNDEF)
2409 // Handle undef ^ undef -> 0 special case. This is a common
2411 return getConstant(0, VT);
2426 return N2; // fold op(arg1, undef) -> undef
2432 return getConstant(0, VT); // fold op(arg1, undef) -> 0
2433 // For vectors, we can't easily build an all zero vector, just return
2438 return getConstant(VT.getIntegerVTBitMask(), VT);
2439 // For vectors, we can't easily build an all one vector, just return
2447 // Memoize this node if possible.
2449 SDVTList VTs = getVTList(VT);
2450 if (VT != MVT::Flag) {
2451 SDOperand Ops[] = { N1, N2 };
2452 FoldingSetNodeID ID;
2453 AddNodeIDNode(ID, Opcode, VTs, Ops, 2);
2455 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2456 return SDOperand(E, 0);
2457 N = new BinarySDNode(Opcode, VTs, N1, N2);
2458 CSEMap.InsertNode(N, IP);
2460 N = new BinarySDNode(Opcode, VTs, N1, N2);
2463 AllNodes.push_back(N);
2464 return SDOperand(N, 0);
2467 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
2468 SDOperand N1, SDOperand N2, SDOperand N3) {
2469 // Perform various simplifications.
2470 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
2471 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
2474 // Use FoldSetCC to simplify SETCC's.
2475 SDOperand Simp = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get());
2476 if (Simp.Val) return Simp;
2481 if (N1C->getValue())
2482 return N2; // select true, X, Y -> X
2484 return N3; // select false, X, Y -> Y
2487 if (N2 == N3) return N2; // select C, X, X -> X
2491 if (N2C->getValue()) // Unconditional branch
2492 return getNode(ISD::BR, MVT::Other, N1, N3);
2494 return N1; // Never-taken branch
2497 case ISD::VECTOR_SHUFFLE:
2498 assert(VT == N1.getValueType() && VT == N2.getValueType() &&
2499 VT.isVector() && N3.getValueType().isVector() &&
2500 N3.getOpcode() == ISD::BUILD_VECTOR &&
2501 VT.getVectorNumElements() == N3.getNumOperands() &&
2502 "Illegal VECTOR_SHUFFLE node!");
2504 case ISD::BIT_CONVERT:
2505 // Fold bit_convert nodes from a type to themselves.
2506 if (N1.getValueType() == VT)
2511 // Memoize node if it doesn't produce a flag.
2513 SDVTList VTs = getVTList(VT);
2514 if (VT != MVT::Flag) {
2515 SDOperand Ops[] = { N1, N2, N3 };
2516 FoldingSetNodeID ID;
2517 AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
2519 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2520 return SDOperand(E, 0);
2521 N = new TernarySDNode(Opcode, VTs, N1, N2, N3);
2522 CSEMap.InsertNode(N, IP);
2524 N = new TernarySDNode(Opcode, VTs, N1, N2, N3);
2526 AllNodes.push_back(N);
2527 return SDOperand(N, 0);
2530 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
2531 SDOperand N1, SDOperand N2, SDOperand N3,
2533 SDOperand Ops[] = { N1, N2, N3, N4 };
2534 return getNode(Opcode, VT, Ops, 4);
2537 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
2538 SDOperand N1, SDOperand N2, SDOperand N3,
2539 SDOperand N4, SDOperand N5) {
2540 SDOperand Ops[] = { N1, N2, N3, N4, N5 };
2541 return getNode(Opcode, VT, Ops, 5);
2544 /// getMemsetValue - Vectorized representation of the memset value
2546 static SDOperand getMemsetValue(SDOperand Value, MVT VT, SelectionDAG &DAG) {
2547 unsigned NumBits = VT.isVector() ?
2548 VT.getVectorElementType().getSizeInBits() : VT.getSizeInBits();
2549 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
2550 APInt Val = APInt(NumBits, C->getValue() & 255);
2552 for (unsigned i = NumBits; i > 8; i >>= 1) {
2553 Val = (Val << Shift) | Val;
2557 return DAG.getConstant(Val, VT);
2558 return DAG.getConstantFP(APFloat(Val), VT);
2561 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
2563 for (unsigned i = NumBits; i > 8; i >>= 1) {
2564 Value = DAG.getNode(ISD::OR, VT,
2565 DAG.getNode(ISD::SHL, VT, Value,
2566 DAG.getConstant(Shift, MVT::i8)), Value);
2573 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
2574 /// used when a memcpy is turned into a memset when the source is a constant
2576 static SDOperand getMemsetStringVal(MVT VT, SelectionDAG &DAG,
2577 const TargetLowering &TLI,
2578 std::string &Str, unsigned Offset) {
2579 // Handle vector with all elements zero.
2582 return DAG.getConstant(0, VT);
2583 unsigned NumElts = VT.getVectorNumElements();
2584 MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
2585 return DAG.getNode(ISD::BIT_CONVERT, VT,
2586 DAG.getConstant(0, MVT::getVectorVT(EltVT, NumElts)));
2589 assert(!VT.isVector() && "Can't handle vector type here!");
2590 unsigned NumBits = VT.getSizeInBits();
2591 unsigned MSB = NumBits / 8;
2593 if (TLI.isLittleEndian())
2594 Offset = Offset + MSB - 1;
2595 for (unsigned i = 0; i != MSB; ++i) {
2596 Val = (Val << 8) | (unsigned char)Str[Offset];
2597 Offset += TLI.isLittleEndian() ? -1 : 1;
2599 return DAG.getConstant(Val, VT);
2602 /// getMemBasePlusOffset - Returns base and offset node for the
2604 static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
2605 SelectionDAG &DAG) {
2606 MVT VT = Base.getValueType();
2607 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
2610 /// isMemSrcFromString - Returns true if memcpy source is a string constant.
2612 static bool isMemSrcFromString(SDOperand Src, std::string &Str) {
2613 unsigned SrcDelta = 0;
2614 GlobalAddressSDNode *G = NULL;
2615 if (Src.getOpcode() == ISD::GlobalAddress)
2616 G = cast<GlobalAddressSDNode>(Src);
2617 else if (Src.getOpcode() == ISD::ADD &&
2618 Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
2619 Src.getOperand(1).getOpcode() == ISD::Constant) {
2620 G = cast<GlobalAddressSDNode>(Src.getOperand(0));
2621 SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getValue();
2626 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
2627 if (GV && GetConstantStringInfo(GV, Str, SrcDelta, false))
2633 /// MeetsMaxMemopRequirement - Determines if the number of memory ops required
2634 /// to replace the memset / memcpy is below the threshold. It also returns the
2635 /// types of the sequence of memory ops to perform memset / memcpy.
2637 bool MeetsMaxMemopRequirement(std::vector<MVT> &MemOps,
2638 SDOperand Dst, SDOperand Src,
2639 unsigned Limit, uint64_t Size, unsigned &Align,
2640 std::string &Str, bool &isSrcStr,
2642 const TargetLowering &TLI) {
2643 isSrcStr = isMemSrcFromString(Src, Str);
2644 bool isSrcConst = isa<ConstantSDNode>(Src);
2645 bool AllowUnalign = TLI.allowsUnalignedMemoryAccesses();
2646 MVT VT= TLI.getOptimalMemOpType(Size, Align, isSrcConst, isSrcStr);
2647 if (VT != MVT::iAny) {
2648 unsigned NewAlign = (unsigned)
2649 TLI.getTargetData()->getABITypeAlignment(VT.getTypeForMVT());
2650 // If source is a string constant, this will require an unaligned load.
2651 if (NewAlign > Align && (isSrcConst || AllowUnalign)) {
2652 if (Dst.getOpcode() != ISD::FrameIndex) {
2653 // Can't change destination alignment. It requires a unaligned store.
2657 int FI = cast<FrameIndexSDNode>(Dst)->getIndex();
2658 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2659 if (MFI->isFixedObjectIndex(FI)) {
2660 // Can't change destination alignment. It requires a unaligned store.
2664 // Give the stack frame object a larger alignment if needed.
2665 if (MFI->getObjectAlignment(FI) < NewAlign)
2666 MFI->setObjectAlignment(FI, NewAlign);
2673 if (VT == MVT::iAny) {
2677 switch (Align & 7) {
2678 case 0: VT = MVT::i64; break;
2679 case 4: VT = MVT::i32; break;
2680 case 2: VT = MVT::i16; break;
2681 default: VT = MVT::i8; break;
2686 while (!TLI.isTypeLegal(LVT))
2687 LVT = (MVT::SimpleValueType)(LVT.getSimpleVT() - 1);
2688 assert(LVT.isInteger());
2694 unsigned NumMemOps = 0;
2696 unsigned VTSize = VT.getSizeInBits() / 8;
2697 while (VTSize > Size) {
2698 // For now, only use non-vector load / store's for the left-over pieces.
2699 if (VT.isVector()) {
2701 while (!TLI.isTypeLegal(VT))
2702 VT = (MVT::SimpleValueType)(VT.getSimpleVT() - 1);
2703 VTSize = VT.getSizeInBits() / 8;
2705 VT = (MVT::SimpleValueType)(VT.getSimpleVT() - 1);
2710 if (++NumMemOps > Limit)
2712 MemOps.push_back(VT);
2719 static SDOperand getMemcpyLoadsAndStores(SelectionDAG &DAG,
2720 SDOperand Chain, SDOperand Dst,
2721 SDOperand Src, uint64_t Size,
2722 unsigned Align, bool AlwaysInline,
2723 const Value *DstSV, uint64_t DstSVOff,
2724 const Value *SrcSV, uint64_t SrcSVOff){
2725 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2727 // Expand memcpy to a series of load and store ops if the size operand falls
2728 // below a certain threshold.
2729 std::vector<MVT> MemOps;
2730 uint64_t Limit = -1;
2732 Limit = TLI.getMaxStoresPerMemcpy();
2733 unsigned DstAlign = Align; // Destination alignment can change.
2736 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, Limit, Size, DstAlign,
2737 Str, CopyFromStr, DAG, TLI))
2741 bool isZeroStr = CopyFromStr && Str.empty();
2742 SmallVector<SDOperand, 8> OutChains;
2743 unsigned NumMemOps = MemOps.size();
2744 uint64_t SrcOff = 0, DstOff = 0;
2745 for (unsigned i = 0; i < NumMemOps; i++) {
2747 unsigned VTSize = VT.getSizeInBits() / 8;
2748 SDOperand Value, Store;
2750 if (CopyFromStr && (isZeroStr || !VT.isVector())) {
2751 // It's unlikely a store of a vector immediate can be done in a single
2752 // instruction. It would require a load from a constantpool first.
2753 // We also handle store a vector with all zero's.
2754 // FIXME: Handle other cases where store of vector immediate is done in
2755 // a single instruction.
2756 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
2757 Store = DAG.getStore(Chain, Value,
2758 getMemBasePlusOffset(Dst, DstOff, DAG),
2759 DstSV, DstSVOff + DstOff);
2761 Value = DAG.getLoad(VT, Chain,
2762 getMemBasePlusOffset(Src, SrcOff, DAG),
2763 SrcSV, SrcSVOff + SrcOff, false, Align);
2764 Store = DAG.getStore(Chain, Value,
2765 getMemBasePlusOffset(Dst, DstOff, DAG),
2766 DstSV, DstSVOff + DstOff, false, DstAlign);
2768 OutChains.push_back(Store);
2773 return DAG.getNode(ISD::TokenFactor, MVT::Other,
2774 &OutChains[0], OutChains.size());
2777 static SDOperand getMemmoveLoadsAndStores(SelectionDAG &DAG,
2778 SDOperand Chain, SDOperand Dst,
2779 SDOperand Src, uint64_t Size,
2780 unsigned Align, bool AlwaysInline,
2781 const Value *DstSV, uint64_t DstSVOff,
2782 const Value *SrcSV, uint64_t SrcSVOff){
2783 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2785 // Expand memmove to a series of load and store ops if the size operand falls
2786 // below a certain threshold.
2787 std::vector<MVT> MemOps;
2788 uint64_t Limit = -1;
2790 Limit = TLI.getMaxStoresPerMemmove();
2791 unsigned DstAlign = Align; // Destination alignment can change.
2794 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, Limit, Size, DstAlign,
2795 Str, CopyFromStr, DAG, TLI))
2798 uint64_t SrcOff = 0, DstOff = 0;
2800 SmallVector<SDOperand, 8> LoadValues;
2801 SmallVector<SDOperand, 8> LoadChains;
2802 SmallVector<SDOperand, 8> OutChains;
2803 unsigned NumMemOps = MemOps.size();
2804 for (unsigned i = 0; i < NumMemOps; i++) {
2806 unsigned VTSize = VT.getSizeInBits() / 8;
2807 SDOperand Value, Store;
2809 Value = DAG.getLoad(VT, Chain,
2810 getMemBasePlusOffset(Src, SrcOff, DAG),
2811 SrcSV, SrcSVOff + SrcOff, false, Align);
2812 LoadValues.push_back(Value);
2813 LoadChains.push_back(Value.getValue(1));
2816 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2817 &LoadChains[0], LoadChains.size());
2819 for (unsigned i = 0; i < NumMemOps; i++) {
2821 unsigned VTSize = VT.getSizeInBits() / 8;
2822 SDOperand Value, Store;
2824 Store = DAG.getStore(Chain, LoadValues[i],
2825 getMemBasePlusOffset(Dst, DstOff, DAG),
2826 DstSV, DstSVOff + DstOff, false, DstAlign);
2827 OutChains.push_back(Store);
2831 return DAG.getNode(ISD::TokenFactor, MVT::Other,
2832 &OutChains[0], OutChains.size());
2835 static SDOperand getMemsetStores(SelectionDAG &DAG,
2836 SDOperand Chain, SDOperand Dst,
2837 SDOperand Src, uint64_t Size,
2839 const Value *DstSV, uint64_t DstSVOff) {
2840 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2842 // Expand memset to a series of load/store ops if the size operand
2843 // falls below a certain threshold.
2844 std::vector<MVT> MemOps;
2847 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, TLI.getMaxStoresPerMemset(),
2848 Size, Align, Str, CopyFromStr, DAG, TLI))
2851 SmallVector<SDOperand, 8> OutChains;
2852 uint64_t DstOff = 0;
2854 unsigned NumMemOps = MemOps.size();
2855 for (unsigned i = 0; i < NumMemOps; i++) {
2857 unsigned VTSize = VT.getSizeInBits() / 8;
2858 SDOperand Value = getMemsetValue(Src, VT, DAG);
2859 SDOperand Store = DAG.getStore(Chain, Value,
2860 getMemBasePlusOffset(Dst, DstOff, DAG),
2861 DstSV, DstSVOff + DstOff);
2862 OutChains.push_back(Store);
2866 return DAG.getNode(ISD::TokenFactor, MVT::Other,
2867 &OutChains[0], OutChains.size());
2870 SDOperand SelectionDAG::getMemcpy(SDOperand Chain, SDOperand Dst,
2871 SDOperand Src, SDOperand Size,
2872 unsigned Align, bool AlwaysInline,
2873 const Value *DstSV, uint64_t DstSVOff,
2874 const Value *SrcSV, uint64_t SrcSVOff) {
2876 // Check to see if we should lower the memcpy to loads and stores first.
2877 // For cases within the target-specified limits, this is the best choice.
2878 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
2880 // Memcpy with size zero? Just return the original chain.
2881 if (ConstantSize->isNullValue())
2885 getMemcpyLoadsAndStores(*this, Chain, Dst, Src, ConstantSize->getValue(),
2886 Align, false, DstSV, DstSVOff, SrcSV, SrcSVOff);
2891 // Then check to see if we should lower the memcpy with target-specific
2892 // code. If the target chooses to do this, this is the next best.
2894 TLI.EmitTargetCodeForMemcpy(*this, Chain, Dst, Src, Size, Align,
2896 DstSV, DstSVOff, SrcSV, SrcSVOff);
2900 // If we really need inline code and the target declined to provide it,
2901 // use a (potentially long) sequence of loads and stores.
2903 assert(ConstantSize && "AlwaysInline requires a constant size!");
2904 return getMemcpyLoadsAndStores(*this, Chain, Dst, Src,
2905 ConstantSize->getValue(), Align, true,
2906 DstSV, DstSVOff, SrcSV, SrcSVOff);
2909 // Emit a library call.
2910 TargetLowering::ArgListTy Args;
2911 TargetLowering::ArgListEntry Entry;
2912 Entry.Ty = TLI.getTargetData()->getIntPtrType();
2913 Entry.Node = Dst; Args.push_back(Entry);
2914 Entry.Node = Src; Args.push_back(Entry);
2915 Entry.Node = Size; Args.push_back(Entry);
2916 std::pair<SDOperand,SDOperand> CallResult =
2917 TLI.LowerCallTo(Chain, Type::VoidTy,
2918 false, false, false, CallingConv::C, false,
2919 getExternalSymbol("memcpy", TLI.getPointerTy()),
2921 return CallResult.second;
2924 SDOperand SelectionDAG::getMemmove(SDOperand Chain, SDOperand Dst,
2925 SDOperand Src, SDOperand Size,
2927 const Value *DstSV, uint64_t DstSVOff,
2928 const Value *SrcSV, uint64_t SrcSVOff) {
2930 // Check to see if we should lower the memmove to loads and stores first.
2931 // For cases within the target-specified limits, this is the best choice.
2932 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
2934 // Memmove with size zero? Just return the original chain.
2935 if (ConstantSize->isNullValue())
2939 getMemmoveLoadsAndStores(*this, Chain, Dst, Src, ConstantSize->getValue(),
2940 Align, false, DstSV, DstSVOff, SrcSV, SrcSVOff);
2945 // Then check to see if we should lower the memmove with target-specific
2946 // code. If the target chooses to do this, this is the next best.
2948 TLI.EmitTargetCodeForMemmove(*this, Chain, Dst, Src, Size, Align,
2949 DstSV, DstSVOff, SrcSV, SrcSVOff);
2953 // Emit a library call.
2954 TargetLowering::ArgListTy Args;
2955 TargetLowering::ArgListEntry Entry;
2956 Entry.Ty = TLI.getTargetData()->getIntPtrType();
2957 Entry.Node = Dst; Args.push_back(Entry);
2958 Entry.Node = Src; Args.push_back(Entry);
2959 Entry.Node = Size; Args.push_back(Entry);
2960 std::pair<SDOperand,SDOperand> CallResult =
2961 TLI.LowerCallTo(Chain, Type::VoidTy,
2962 false, false, false, CallingConv::C, false,
2963 getExternalSymbol("memmove", TLI.getPointerTy()),
2965 return CallResult.second;
2968 SDOperand SelectionDAG::getMemset(SDOperand Chain, SDOperand Dst,
2969 SDOperand Src, SDOperand Size,
2971 const Value *DstSV, uint64_t DstSVOff) {
2973 // Check to see if we should lower the memset to stores first.
2974 // For cases within the target-specified limits, this is the best choice.
2975 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
2977 // Memset with size zero? Just return the original chain.
2978 if (ConstantSize->isNullValue())
2982 getMemsetStores(*this, Chain, Dst, Src, ConstantSize->getValue(), Align,
2988 // Then check to see if we should lower the memset with target-specific
2989 // code. If the target chooses to do this, this is the next best.
2991 TLI.EmitTargetCodeForMemset(*this, Chain, Dst, Src, Size, Align,
2996 // Emit a library call.
2997 const Type *IntPtrTy = TLI.getTargetData()->getIntPtrType();
2998 TargetLowering::ArgListTy Args;
2999 TargetLowering::ArgListEntry Entry;
3000 Entry.Node = Dst; Entry.Ty = IntPtrTy;
3001 Args.push_back(Entry);
3002 // Extend or truncate the argument to be an i32 value for the call.
3003 if (Src.getValueType().bitsGT(MVT::i32))
3004 Src = getNode(ISD::TRUNCATE, MVT::i32, Src);
3006 Src = getNode(ISD::ZERO_EXTEND, MVT::i32, Src);
3007 Entry.Node = Src; Entry.Ty = Type::Int32Ty; Entry.isSExt = true;
3008 Args.push_back(Entry);
3009 Entry.Node = Size; Entry.Ty = IntPtrTy; Entry.isSExt = false;
3010 Args.push_back(Entry);
3011 std::pair<SDOperand,SDOperand> CallResult =
3012 TLI.LowerCallTo(Chain, Type::VoidTy,
3013 false, false, false, CallingConv::C, false,
3014 getExternalSymbol("memset", TLI.getPointerTy()),
3016 return CallResult.second;
3019 SDOperand SelectionDAG::getAtomic(unsigned Opcode, SDOperand Chain,
3020 SDOperand Ptr, SDOperand Cmp,
3021 SDOperand Swp, const Value* PtrVal,
3022 unsigned Alignment) {
3023 assert(Opcode == ISD::ATOMIC_CMP_SWAP && "Invalid Atomic Op");
3024 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
3025 SDVTList VTs = getVTList(Cmp.getValueType(), MVT::Other);
3026 FoldingSetNodeID ID;
3027 SDOperand Ops[] = {Chain, Ptr, Cmp, Swp};
3028 AddNodeIDNode(ID, Opcode, VTs, Ops, 4);
3030 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3031 return SDOperand(E, 0);
3032 SDNode* N = new AtomicSDNode(Opcode, VTs, Chain, Ptr, Cmp, Swp,
3034 CSEMap.InsertNode(N, IP);
3035 AllNodes.push_back(N);
3036 return SDOperand(N, 0);
3039 SDOperand SelectionDAG::getAtomic(unsigned Opcode, SDOperand Chain,
3040 SDOperand Ptr, SDOperand Val,
3041 const Value* PtrVal,
3042 unsigned Alignment) {
3043 assert(( Opcode == ISD::ATOMIC_LOAD_ADD || Opcode == ISD::ATOMIC_LOAD_SUB
3044 || Opcode == ISD::ATOMIC_SWAP || Opcode == ISD::ATOMIC_LOAD_AND
3045 || Opcode == ISD::ATOMIC_LOAD_OR || Opcode == ISD::ATOMIC_LOAD_XOR
3046 || Opcode == ISD::ATOMIC_LOAD_NAND
3047 || Opcode == ISD::ATOMIC_LOAD_MIN || Opcode == ISD::ATOMIC_LOAD_MAX
3048 || Opcode == ISD::ATOMIC_LOAD_UMIN || Opcode == ISD::ATOMIC_LOAD_UMAX)
3049 && "Invalid Atomic Op");
3050 SDVTList VTs = getVTList(Val.getValueType(), MVT::Other);
3051 FoldingSetNodeID ID;
3052 SDOperand Ops[] = {Chain, Ptr, Val};
3053 AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
3055 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3056 return SDOperand(E, 0);
3057 SDNode* N = new AtomicSDNode(Opcode, VTs, Chain, Ptr, Val,
3059 CSEMap.InsertNode(N, IP);
3060 AllNodes.push_back(N);
3061 return SDOperand(N, 0);
3064 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
3065 /// Allowed to return something different (and simpler) if Simplify is true.
3066 SDOperand SelectionDAG::getMergeValues(const SDOperand *Ops, unsigned NumOps,
3068 if (Simplify && NumOps == 1)
3071 SmallVector<MVT, 4> VTs;
3072 VTs.reserve(NumOps);
3073 for (unsigned i = 0; i < NumOps; ++i)
3074 VTs.push_back(Ops[i].getValueType());
3075 return getNode(ISD::MERGE_VALUES, getVTList(&VTs[0], NumOps), Ops, NumOps);
3079 SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
3080 MVT VT, SDOperand Chain,
3081 SDOperand Ptr, SDOperand Offset,
3082 const Value *SV, int SVOffset, MVT EVT,
3083 bool isVolatile, unsigned Alignment) {
3084 if (Alignment == 0) { // Ensure that codegen never sees alignment 0
3086 if (VT != MVT::iPTR) {
3087 Ty = VT.getTypeForMVT();
3089 const PointerType *PT = dyn_cast<PointerType>(SV->getType());
3090 assert(PT && "Value for load must be a pointer");
3091 Ty = PT->getElementType();
3093 assert(Ty && "Could not get type information for load");
3094 Alignment = TLI.getTargetData()->getABITypeAlignment(Ty);
3098 ExtType = ISD::NON_EXTLOAD;
3099 } else if (ExtType == ISD::NON_EXTLOAD) {
3100 assert(VT == EVT && "Non-extending load from different memory type!");
3104 assert(EVT == VT.getVectorElementType() && "Invalid vector extload!");
3106 assert(EVT.bitsLT(VT) &&
3107 "Should only be an extending load, not truncating!");
3108 assert((ExtType == ISD::EXTLOAD || VT.isInteger()) &&
3109 "Cannot sign/zero extend a FP/Vector load!");
3110 assert(VT.isInteger() == EVT.isInteger() &&
3111 "Cannot convert from FP to Int or Int -> FP!");
3114 bool Indexed = AM != ISD::UNINDEXED;
3115 assert((Indexed || Offset.getOpcode() == ISD::UNDEF) &&
3116 "Unindexed load with an offset!");
3118 SDVTList VTs = Indexed ?
3119 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
3120 SDOperand Ops[] = { Chain, Ptr, Offset };
3121 FoldingSetNodeID ID;
3122 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops, 3);
3124 ID.AddInteger(ExtType);
3125 ID.AddInteger(EVT.getRawBits());
3126 ID.AddInteger(Alignment);
3127 ID.AddInteger(isVolatile);
3129 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3130 return SDOperand(E, 0);
3131 SDNode *N = new LoadSDNode(Ops, VTs, AM, ExtType, EVT, SV, SVOffset,
3132 Alignment, isVolatile);
3133 CSEMap.InsertNode(N, IP);
3134 AllNodes.push_back(N);
3135 return SDOperand(N, 0);
3138 SDOperand SelectionDAG::getLoad(MVT VT,
3139 SDOperand Chain, SDOperand Ptr,
3140 const Value *SV, int SVOffset,
3141 bool isVolatile, unsigned Alignment) {
3142 SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3143 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, Chain, Ptr, Undef,
3144 SV, SVOffset, VT, isVolatile, Alignment);
3147 SDOperand SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, MVT VT,
3148 SDOperand Chain, SDOperand Ptr,
3150 int SVOffset, MVT EVT,
3151 bool isVolatile, unsigned Alignment) {
3152 SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3153 return getLoad(ISD::UNINDEXED, ExtType, VT, Chain, Ptr, Undef,
3154 SV, SVOffset, EVT, isVolatile, Alignment);
3158 SelectionDAG::getIndexedLoad(SDOperand OrigLoad, SDOperand Base,
3159 SDOperand Offset, ISD::MemIndexedMode AM) {
3160 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
3161 assert(LD->getOffset().getOpcode() == ISD::UNDEF &&
3162 "Load is already a indexed load!");
3163 return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(),
3164 LD->getChain(), Base, Offset, LD->getSrcValue(),
3165 LD->getSrcValueOffset(), LD->getMemoryVT(),
3166 LD->isVolatile(), LD->getAlignment());
3169 SDOperand SelectionDAG::getStore(SDOperand Chain, SDOperand Val,
3170 SDOperand Ptr, const Value *SV, int SVOffset,
3171 bool isVolatile, unsigned Alignment) {
3172 MVT VT = Val.getValueType();
3174 if (Alignment == 0) { // Ensure that codegen never sees alignment 0
3176 if (VT != MVT::iPTR) {
3177 Ty = VT.getTypeForMVT();
3179 const PointerType *PT = dyn_cast<PointerType>(SV->getType());
3180 assert(PT && "Value for store must be a pointer");
3181 Ty = PT->getElementType();
3183 assert(Ty && "Could not get type information for store");
3184 Alignment = TLI.getTargetData()->getABITypeAlignment(Ty);
3186 SDVTList VTs = getVTList(MVT::Other);
3187 SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3188 SDOperand Ops[] = { Chain, Val, Ptr, Undef };
3189 FoldingSetNodeID ID;
3190 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3191 ID.AddInteger(ISD::UNINDEXED);
3192 ID.AddInteger(false);
3193 ID.AddInteger(VT.getRawBits());
3194 ID.AddInteger(Alignment);
3195 ID.AddInteger(isVolatile);
3197 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3198 return SDOperand(E, 0);
3199 SDNode *N = new StoreSDNode(Ops, VTs, ISD::UNINDEXED, false,
3200 VT, SV, SVOffset, Alignment, isVolatile);
3201 CSEMap.InsertNode(N, IP);
3202 AllNodes.push_back(N);
3203 return SDOperand(N, 0);
3206 SDOperand SelectionDAG::getTruncStore(SDOperand Chain, SDOperand Val,
3207 SDOperand Ptr, const Value *SV,
3208 int SVOffset, MVT SVT,
3209 bool isVolatile, unsigned Alignment) {
3210 MVT VT = Val.getValueType();
3213 return getStore(Chain, Val, Ptr, SV, SVOffset, isVolatile, Alignment);
3215 assert(VT.bitsGT(SVT) && "Not a truncation?");
3216 assert(VT.isInteger() == SVT.isInteger() &&
3217 "Can't do FP-INT conversion!");
3219 if (Alignment == 0) { // Ensure that codegen never sees alignment 0
3221 if (VT != MVT::iPTR) {
3222 Ty = VT.getTypeForMVT();
3224 const PointerType *PT = dyn_cast<PointerType>(SV->getType());
3225 assert(PT && "Value for store must be a pointer");
3226 Ty = PT->getElementType();
3228 assert(Ty && "Could not get type information for store");
3229 Alignment = TLI.getTargetData()->getABITypeAlignment(Ty);
3231 SDVTList VTs = getVTList(MVT::Other);
3232 SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3233 SDOperand Ops[] = { Chain, Val, Ptr, Undef };
3234 FoldingSetNodeID ID;
3235 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3236 ID.AddInteger(ISD::UNINDEXED);
3238 ID.AddInteger(SVT.getRawBits());
3239 ID.AddInteger(Alignment);
3240 ID.AddInteger(isVolatile);
3242 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3243 return SDOperand(E, 0);
3244 SDNode *N = new StoreSDNode(Ops, VTs, ISD::UNINDEXED, true,
3245 SVT, SV, SVOffset, Alignment, isVolatile);
3246 CSEMap.InsertNode(N, IP);
3247 AllNodes.push_back(N);
3248 return SDOperand(N, 0);
3252 SelectionDAG::getIndexedStore(SDOperand OrigStore, SDOperand Base,
3253 SDOperand Offset, ISD::MemIndexedMode AM) {
3254 StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
3255 assert(ST->getOffset().getOpcode() == ISD::UNDEF &&
3256 "Store is already a indexed store!");
3257 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
3258 SDOperand Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
3259 FoldingSetNodeID ID;
3260 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3262 ID.AddInteger(ST->isTruncatingStore());
3263 ID.AddInteger(ST->getMemoryVT().getRawBits());
3264 ID.AddInteger(ST->getAlignment());
3265 ID.AddInteger(ST->isVolatile());
3267 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3268 return SDOperand(E, 0);
3269 SDNode *N = new StoreSDNode(Ops, VTs, AM,
3270 ST->isTruncatingStore(), ST->getMemoryVT(),
3271 ST->getSrcValue(), ST->getSrcValueOffset(),
3272 ST->getAlignment(), ST->isVolatile());
3273 CSEMap.InsertNode(N, IP);
3274 AllNodes.push_back(N);
3275 return SDOperand(N, 0);
3278 SDOperand SelectionDAG::getVAArg(MVT VT,
3279 SDOperand Chain, SDOperand Ptr,
3281 SDOperand Ops[] = { Chain, Ptr, SV };
3282 return getNode(ISD::VAARG, getVTList(VT, MVT::Other), Ops, 3);
3285 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
3286 const SDUse *Ops, unsigned NumOps) {
3288 case 0: return getNode(Opcode, VT);
3289 case 1: return getNode(Opcode, VT, Ops[0].getSDOperand());
3290 case 2: return getNode(Opcode, VT, Ops[0].getSDOperand(),
3291 Ops[1].getSDOperand());
3292 case 3: return getNode(Opcode, VT, Ops[0].getSDOperand(),
3293 Ops[1].getSDOperand(), Ops[2].getSDOperand());
3297 // Copy from an SDUse array into an SDOperand array for use with
3298 // the regular getNode logic.
3299 SmallVector<SDOperand, 8> NewOps;
3300 NewOps.reserve(NumOps);
3301 for (unsigned i = 0; i != NumOps; ++i)
3302 NewOps.push_back(Ops[i].getSDOperand());
3303 return getNode(Opcode, VT, Ops, NumOps);
3306 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
3307 const SDOperand *Ops, unsigned NumOps) {
3309 case 0: return getNode(Opcode, VT);
3310 case 1: return getNode(Opcode, VT, Ops[0]);
3311 case 2: return getNode(Opcode, VT, Ops[0], Ops[1]);
3312 case 3: return getNode(Opcode, VT, Ops[0], Ops[1], Ops[2]);
3318 case ISD::SELECT_CC: {
3319 assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
3320 assert(Ops[0].getValueType() == Ops[1].getValueType() &&
3321 "LHS and RHS of condition must have same type!");
3322 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
3323 "True and False arms of SelectCC must have same type!");
3324 assert(Ops[2].getValueType() == VT &&
3325 "select_cc node must be of same type as true and false value!");
3329 assert(NumOps == 5 && "BR_CC takes 5 operands!");
3330 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
3331 "LHS/RHS of comparison should match types!");
3338 SDVTList VTs = getVTList(VT);
3339 if (VT != MVT::Flag) {
3340 FoldingSetNodeID ID;
3341 AddNodeIDNode(ID, Opcode, VTs, Ops, NumOps);
3343 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3344 return SDOperand(E, 0);
3345 N = new SDNode(Opcode, VTs, Ops, NumOps);
3346 CSEMap.InsertNode(N, IP);
3348 N = new SDNode(Opcode, VTs, Ops, NumOps);
3350 AllNodes.push_back(N);
3351 return SDOperand(N, 0);
3354 SDOperand SelectionDAG::getNode(unsigned Opcode,
3355 std::vector<MVT> &ResultTys,
3356 const SDOperand *Ops, unsigned NumOps) {
3357 return getNode(Opcode, getNodeValueTypes(ResultTys), ResultTys.size(),
3361 SDOperand SelectionDAG::getNode(unsigned Opcode,
3362 const MVT *VTs, unsigned NumVTs,
3363 const SDOperand *Ops, unsigned NumOps) {
3365 return getNode(Opcode, VTs[0], Ops, NumOps);
3366 return getNode(Opcode, makeVTList(VTs, NumVTs), Ops, NumOps);
3369 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3370 const SDOperand *Ops, unsigned NumOps) {
3371 if (VTList.NumVTs == 1)
3372 return getNode(Opcode, VTList.VTs[0], Ops, NumOps);
3375 // FIXME: figure out how to safely handle things like
3376 // int foo(int x) { return 1 << (x & 255); }
3377 // int bar() { return foo(256); }
3379 case ISD::SRA_PARTS:
3380 case ISD::SRL_PARTS:
3381 case ISD::SHL_PARTS:
3382 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
3383 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
3384 return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
3385 else if (N3.getOpcode() == ISD::AND)
3386 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
3387 // If the and is only masking out bits that cannot effect the shift,
3388 // eliminate the and.
3389 unsigned NumBits = VT.getSizeInBits()*2;
3390 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
3391 return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
3397 // Memoize the node unless it returns a flag.
3399 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
3400 FoldingSetNodeID ID;
3401 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
3403 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3404 return SDOperand(E, 0);
3406 N = new UnarySDNode(Opcode, VTList, Ops[0]);
3407 else if (NumOps == 2)
3408 N = new BinarySDNode(Opcode, VTList, Ops[0], Ops[1]);
3409 else if (NumOps == 3)
3410 N = new TernarySDNode(Opcode, VTList, Ops[0], Ops[1], Ops[2]);
3412 N = new SDNode(Opcode, VTList, Ops, NumOps);
3413 CSEMap.InsertNode(N, IP);
3416 N = new UnarySDNode(Opcode, VTList, Ops[0]);
3417 else if (NumOps == 2)
3418 N = new BinarySDNode(Opcode, VTList, Ops[0], Ops[1]);
3419 else if (NumOps == 3)
3420 N = new TernarySDNode(Opcode, VTList, Ops[0], Ops[1], Ops[2]);
3422 N = new SDNode(Opcode, VTList, Ops, NumOps);
3424 AllNodes.push_back(N);
3425 return SDOperand(N, 0);
3428 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList) {
3429 return getNode(Opcode, VTList, 0, 0);
3432 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3434 SDOperand Ops[] = { N1 };
3435 return getNode(Opcode, VTList, Ops, 1);
3438 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3439 SDOperand N1, SDOperand N2) {
3440 SDOperand Ops[] = { N1, N2 };
3441 return getNode(Opcode, VTList, Ops, 2);
3444 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3445 SDOperand N1, SDOperand N2, SDOperand N3) {
3446 SDOperand Ops[] = { N1, N2, N3 };
3447 return getNode(Opcode, VTList, Ops, 3);
3450 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3451 SDOperand N1, SDOperand N2, SDOperand N3,
3453 SDOperand Ops[] = { N1, N2, N3, N4 };
3454 return getNode(Opcode, VTList, Ops, 4);
3457 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3458 SDOperand N1, SDOperand N2, SDOperand N3,
3459 SDOperand N4, SDOperand N5) {
3460 SDOperand Ops[] = { N1, N2, N3, N4, N5 };
3461 return getNode(Opcode, VTList, Ops, 5);
3464 SDVTList SelectionDAG::getVTList(MVT VT) {
3465 return makeVTList(SDNode::getValueTypeList(VT), 1);
3468 SDVTList SelectionDAG::getVTList(MVT VT1, MVT VT2) {
3469 for (std::list<std::vector<MVT> >::iterator I = VTList.begin(),
3470 E = VTList.end(); I != E; ++I) {
3471 if (I->size() == 2 && (*I)[0] == VT1 && (*I)[1] == VT2)
3472 return makeVTList(&(*I)[0], 2);
3477 VTList.push_front(V);
3478 return makeVTList(&(*VTList.begin())[0], 2);
3480 SDVTList SelectionDAG::getVTList(MVT VT1, MVT VT2,
3482 for (std::list<std::vector<MVT> >::iterator I = VTList.begin(),
3483 E = VTList.end(); I != E; ++I) {
3484 if (I->size() == 3 && (*I)[0] == VT1 && (*I)[1] == VT2 &&
3486 return makeVTList(&(*I)[0], 3);
3492 VTList.push_front(V);
3493 return makeVTList(&(*VTList.begin())[0], 3);
3496 SDVTList SelectionDAG::getVTList(const MVT *VTs, unsigned NumVTs) {
3498 case 0: assert(0 && "Cannot have nodes without results!");
3499 case 1: return getVTList(VTs[0]);
3500 case 2: return getVTList(VTs[0], VTs[1]);
3501 case 3: return getVTList(VTs[0], VTs[1], VTs[2]);
3505 for (std::list<std::vector<MVT> >::iterator I = VTList.begin(),
3506 E = VTList.end(); I != E; ++I) {
3507 if (I->size() != NumVTs || VTs[0] != (*I)[0] || VTs[1] != (*I)[1]) continue;
3509 bool NoMatch = false;
3510 for (unsigned i = 2; i != NumVTs; ++i)
3511 if (VTs[i] != (*I)[i]) {
3516 return makeVTList(&*I->begin(), NumVTs);
3519 VTList.push_front(std::vector<MVT>(VTs, VTs+NumVTs));
3520 return makeVTList(&*VTList.begin()->begin(), NumVTs);
3524 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
3525 /// specified operands. If the resultant node already exists in the DAG,
3526 /// this does not modify the specified node, instead it returns the node that
3527 /// already exists. If the resultant node does not exist in the DAG, the
3528 /// input node is returned. As a degenerate case, if you specify the same
3529 /// input operands as the node already has, the input node is returned.
3530 SDOperand SelectionDAG::
3531 UpdateNodeOperands(SDOperand InN, SDOperand Op) {
3532 SDNode *N = InN.Val;
3533 assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
3535 // Check to see if there is no change.
3536 if (Op == N->getOperand(0)) return InN;
3538 // See if the modified node already exists.
3539 void *InsertPos = 0;
3540 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
3541 return SDOperand(Existing, InN.ResNo);
3543 // Nope it doesn't. Remove the node from it's current place in the maps.
3545 RemoveNodeFromCSEMaps(N);
3547 // Now we update the operands.
3548 N->OperandList[0].getVal()->removeUser(0, N);
3549 N->OperandList[0] = Op;
3550 N->OperandList[0].setUser(N);
3551 Op.Val->addUser(0, N);
3553 // If this gets put into a CSE map, add it.
3554 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
3558 SDOperand SelectionDAG::
3559 UpdateNodeOperands(SDOperand InN, SDOperand Op1, SDOperand Op2) {
3560 SDNode *N = InN.Val;
3561 assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
3563 // Check to see if there is no change.
3564 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
3565 return InN; // No operands changed, just return the input node.
3567 // See if the modified node already exists.
3568 void *InsertPos = 0;
3569 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
3570 return SDOperand(Existing, InN.ResNo);
3572 // Nope it doesn't. Remove the node from it's current place in the maps.
3574 RemoveNodeFromCSEMaps(N);
3576 // Now we update the operands.
3577 if (N->OperandList[0] != Op1) {
3578 N->OperandList[0].getVal()->removeUser(0, N);
3579 N->OperandList[0] = Op1;
3580 N->OperandList[0].setUser(N);
3581 Op1.Val->addUser(0, N);
3583 if (N->OperandList[1] != Op2) {
3584 N->OperandList[1].getVal()->removeUser(1, N);
3585 N->OperandList[1] = Op2;
3586 N->OperandList[1].setUser(N);
3587 Op2.Val->addUser(1, N);
3590 // If this gets put into a CSE map, add it.
3591 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
3595 SDOperand SelectionDAG::
3596 UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2, SDOperand Op3) {
3597 SDOperand Ops[] = { Op1, Op2, Op3 };
3598 return UpdateNodeOperands(N, Ops, 3);
3601 SDOperand SelectionDAG::
3602 UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2,
3603 SDOperand Op3, SDOperand Op4) {
3604 SDOperand Ops[] = { Op1, Op2, Op3, Op4 };
3605 return UpdateNodeOperands(N, Ops, 4);
3608 SDOperand SelectionDAG::
3609 UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2,
3610 SDOperand Op3, SDOperand Op4, SDOperand Op5) {
3611 SDOperand Ops[] = { Op1, Op2, Op3, Op4, Op5 };
3612 return UpdateNodeOperands(N, Ops, 5);
3615 SDOperand SelectionDAG::
3616 UpdateNodeOperands(SDOperand InN, const SDOperand *Ops, unsigned NumOps) {
3617 SDNode *N = InN.Val;
3618 assert(N->getNumOperands() == NumOps &&
3619 "Update with wrong number of operands");
3621 // Check to see if there is no change.
3622 bool AnyChange = false;
3623 for (unsigned i = 0; i != NumOps; ++i) {
3624 if (Ops[i] != N->getOperand(i)) {
3630 // No operands changed, just return the input node.
3631 if (!AnyChange) return InN;
3633 // See if the modified node already exists.
3634 void *InsertPos = 0;
3635 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, NumOps, InsertPos))
3636 return SDOperand(Existing, InN.ResNo);
3638 // Nope it doesn't. Remove the node from its current place in the maps.
3640 RemoveNodeFromCSEMaps(N);
3642 // Now we update the operands.
3643 for (unsigned i = 0; i != NumOps; ++i) {
3644 if (N->OperandList[i] != Ops[i]) {
3645 N->OperandList[i].getVal()->removeUser(i, N);
3646 N->OperandList[i] = Ops[i];
3647 N->OperandList[i].setUser(N);
3648 Ops[i].Val->addUser(i, N);
3652 // If this gets put into a CSE map, add it.
3653 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
3657 /// MorphNodeTo - This frees the operands of the current node, resets the
3658 /// opcode, types, and operands to the specified value. This should only be
3659 /// used by the SelectionDAG class.
3660 void SDNode::MorphNodeTo(unsigned Opc, SDVTList L,
3661 const SDOperand *Ops, unsigned NumOps,
3662 SmallVectorImpl<SDNode *> &DeadNodes) {
3665 NumValues = L.NumVTs;
3667 // Clear the operands list, updating used nodes to remove this from their
3668 // use list. Keep track of any operands that become dead as a result.
3669 SmallPtrSet<SDNode*, 16> DeadNodeSet;
3670 for (op_iterator I = op_begin(), E = op_end(); I != E; ++I) {
3671 SDNode *N = I->getVal();
3672 N->removeUser(std::distance(op_begin(), I), this);
3674 DeadNodeSet.insert(N);
3677 // If NumOps is larger than the # of operands we currently have, reallocate
3678 // the operand list.
3679 if (NumOps > NumOperands) {
3680 if (OperandsNeedDelete) {
3681 delete [] OperandList;
3683 OperandList = new SDUse[NumOps];
3684 OperandsNeedDelete = true;
3687 // Assign the new operands.
3688 NumOperands = NumOps;
3690 for (unsigned i = 0, e = NumOps; i != e; ++i) {
3691 OperandList[i] = Ops[i];
3692 OperandList[i].setUser(this);
3693 SDNode *N = OperandList[i].getVal();
3694 N->addUser(i, this);
3696 DeadNodeSet.erase(N);
3699 // Clean up any nodes that are still dead after adding the uses for the
3701 for (SmallPtrSet<SDNode *, 16>::iterator I = DeadNodeSet.begin(),
3702 E = DeadNodeSet.end(); I != E; ++I)
3703 DeadNodes.push_back(*I);
3706 /// DropOperands - Release the operands and set this node to have
3707 /// zero operands. This should only be used by HandleSDNode to clear
3708 /// its operand list.
3709 void SDNode::DropOperands() {
3710 assert(NodeType == ISD::HANDLENODE &&
3711 "DropOperands is for HANDLENODE only!");
3713 // Unlike the code in MorphNodeTo that does this, we don't need to
3714 // watch for dead nodes here.
3715 for (op_iterator I = op_begin(), E = op_end(); I != E; ++I)
3716 I->getVal()->removeUser(std::distance(op_begin(), I), this);
3721 /// SelectNodeTo - These are used for target selectors to *mutate* the
3722 /// specified node to have the specified return type, Target opcode, and
3723 /// operands. Note that target opcodes are stored as
3724 /// ISD::BUILTIN_OP_END+TargetOpcode in the node opcode field.
3726 /// Note that SelectNodeTo returns the resultant node. If there is already a
3727 /// node of the specified opcode and operands, it returns that node instead of
3728 /// the current one.
3729 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3731 SDVTList VTs = getVTList(VT);
3732 return SelectNodeTo(N, TargetOpc, VTs, 0, 0);
3735 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3736 MVT VT, SDOperand Op1) {
3737 SDVTList VTs = getVTList(VT);
3738 SDOperand Ops[] = { Op1 };
3739 return SelectNodeTo(N, TargetOpc, VTs, Ops, 1);
3742 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3743 MVT VT, SDOperand Op1,
3745 SDVTList VTs = getVTList(VT);
3746 SDOperand Ops[] = { Op1, Op2 };
3747 return SelectNodeTo(N, TargetOpc, VTs, Ops, 2);
3750 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3751 MVT VT, SDOperand Op1,
3752 SDOperand Op2, SDOperand Op3) {
3753 SDVTList VTs = getVTList(VT);
3754 SDOperand Ops[] = { Op1, Op2, Op3 };
3755 return SelectNodeTo(N, TargetOpc, VTs, Ops, 3);
3758 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3759 MVT VT, const SDOperand *Ops,
3761 SDVTList VTs = getVTList(VT);
3762 return SelectNodeTo(N, TargetOpc, VTs, Ops, NumOps);
3765 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3766 MVT VT1, MVT VT2, const SDOperand *Ops,
3768 SDVTList VTs = getVTList(VT1, VT2);
3769 return SelectNodeTo(N, TargetOpc, VTs, Ops, NumOps);
3772 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3774 SDVTList VTs = getVTList(VT1, VT2);
3775 return SelectNodeTo(N, TargetOpc, VTs, (SDOperand *)0, 0);
3778 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3779 MVT VT1, MVT VT2, MVT VT3,
3780 const SDOperand *Ops, unsigned NumOps) {
3781 SDVTList VTs = getVTList(VT1, VT2, VT3);
3782 return SelectNodeTo(N, TargetOpc, VTs, Ops, NumOps);
3785 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3788 SDVTList VTs = getVTList(VT1, VT2);
3789 SDOperand Ops[] = { Op1 };
3790 return SelectNodeTo(N, TargetOpc, VTs, Ops, 1);
3793 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3795 SDOperand Op1, SDOperand Op2) {
3796 SDVTList VTs = getVTList(VT1, VT2);
3797 SDOperand Ops[] = { Op1, Op2 };
3798 return SelectNodeTo(N, TargetOpc, VTs, Ops, 2);
3801 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3803 SDOperand Op1, SDOperand Op2,
3805 SDVTList VTs = getVTList(VT1, VT2);
3806 SDOperand Ops[] = { Op1, Op2, Op3 };
3807 return SelectNodeTo(N, TargetOpc, VTs, Ops, 3);
3810 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3811 SDVTList VTs, const SDOperand *Ops,
3813 // If an identical node already exists, use it.
3814 FoldingSetNodeID ID;
3815 AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, NumOps);
3817 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3820 RemoveNodeFromCSEMaps(N);
3822 SmallVector<SDNode *, 16> DeadNodes;
3823 N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, NumOps, DeadNodes);
3824 RemoveDeadNodes(DeadNodes);
3826 CSEMap.InsertNode(N, IP); // Memoize the new node.
3831 /// getTargetNode - These are used for target selectors to create a new node
3832 /// with specified return type(s), target opcode, and operands.
3834 /// Note that getTargetNode returns the resultant node. If there is already a
3835 /// node of the specified opcode and operands, it returns that node instead of
3836 /// the current one.
3837 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT) {
3838 return getNode(ISD::BUILTIN_OP_END+Opcode, VT).Val;
3840 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT, SDOperand Op1) {
3841 return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1).Val;
3843 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT,
3844 SDOperand Op1, SDOperand Op2) {
3845 return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1, Op2).Val;
3847 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT,
3848 SDOperand Op1, SDOperand Op2,
3850 return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1, Op2, Op3).Val;
3852 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT,
3853 const SDOperand *Ops, unsigned NumOps) {
3854 return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Ops, NumOps).Val;
3856 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2) {
3857 const MVT *VTs = getNodeValueTypes(VT1, VT2);
3859 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, &Op, 0).Val;
3861 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
3862 MVT VT2, SDOperand Op1) {
3863 const MVT *VTs = getNodeValueTypes(VT1, VT2);
3864 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, &Op1, 1).Val;
3866 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
3867 MVT VT2, SDOperand Op1,
3869 const MVT *VTs = getNodeValueTypes(VT1, VT2);
3870 SDOperand Ops[] = { Op1, Op2 };
3871 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, Ops, 2).Val;
3873 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
3874 MVT VT2, SDOperand Op1,
3875 SDOperand Op2, SDOperand Op3) {
3876 const MVT *VTs = getNodeValueTypes(VT1, VT2);
3877 SDOperand Ops[] = { Op1, Op2, Op3 };
3878 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, Ops, 3).Val;
3880 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2,
3881 const SDOperand *Ops, unsigned NumOps) {
3882 const MVT *VTs = getNodeValueTypes(VT1, VT2);
3883 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, Ops, NumOps).Val;
3885 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2, MVT VT3,
3886 SDOperand Op1, SDOperand Op2) {
3887 const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
3888 SDOperand Ops[] = { Op1, Op2 };
3889 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 3, Ops, 2).Val;
3891 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2, MVT VT3,
3892 SDOperand Op1, SDOperand Op2,
3894 const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
3895 SDOperand Ops[] = { Op1, Op2, Op3 };
3896 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 3, Ops, 3).Val;
3898 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2, MVT VT3,
3899 const SDOperand *Ops, unsigned NumOps) {
3900 const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
3901 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 3, Ops, NumOps).Val;
3903 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
3904 MVT VT2, MVT VT3, MVT VT4,
3905 const SDOperand *Ops, unsigned NumOps) {
3906 std::vector<MVT> VTList;
3907 VTList.push_back(VT1);
3908 VTList.push_back(VT2);
3909 VTList.push_back(VT3);
3910 VTList.push_back(VT4);
3911 const MVT *VTs = getNodeValueTypes(VTList);
3912 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 4, Ops, NumOps).Val;
3914 SDNode *SelectionDAG::getTargetNode(unsigned Opcode,
3915 std::vector<MVT> &ResultTys,
3916 const SDOperand *Ops, unsigned NumOps) {
3917 const MVT *VTs = getNodeValueTypes(ResultTys);
3918 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, ResultTys.size(),
3922 /// getNodeIfExists - Get the specified node if it's already available, or
3923 /// else return NULL.
3924 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
3925 const SDOperand *Ops, unsigned NumOps) {
3926 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
3927 FoldingSetNodeID ID;
3928 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
3930 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3937 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
3938 /// This can cause recursive merging of nodes in the DAG.
3940 /// This version assumes From has a single result value.
3942 void SelectionDAG::ReplaceAllUsesWith(SDOperand FromN, SDOperand To,
3943 DAGUpdateListener *UpdateListener) {
3944 SDNode *From = FromN.Val;
3945 assert(From->getNumValues() == 1 && FromN.ResNo == 0 &&
3946 "Cannot replace with this method!");
3947 assert(From != To.Val && "Cannot replace uses of with self");
3949 while (!From->use_empty()) {
3950 SDNode::use_iterator UI = From->use_begin();
3951 SDNode *U = UI->getUser();
3953 // This node is about to morph, remove its old self from the CSE maps.
3954 RemoveNodeFromCSEMaps(U);
3956 for (SDNode::op_iterator I = U->op_begin(), E = U->op_end();
3957 I != E; ++I, ++operandNum)
3958 if (I->getVal() == From) {
3959 From->removeUser(operandNum, U);
3962 To.Val->addUser(operandNum, U);
3965 // Now that we have modified U, add it back to the CSE maps. If it already
3966 // exists there, recursively merge the results together.
3967 if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
3968 ReplaceAllUsesWith(U, Existing, UpdateListener);
3969 // U is now dead. Inform the listener if it exists and delete it.
3971 UpdateListener->NodeDeleted(U, Existing);
3972 DeleteNodeNotInCSEMaps(U);
3974 // If the node doesn't already exist, we updated it. Inform a listener if
3977 UpdateListener->NodeUpdated(U);
3982 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
3983 /// This can cause recursive merging of nodes in the DAG.
3985 /// This version assumes From/To have matching types and numbers of result
3988 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To,
3989 DAGUpdateListener *UpdateListener) {
3990 assert(From != To && "Cannot replace uses of with self");
3991 assert(From->getNumValues() == To->getNumValues() &&
3992 "Cannot use this version of ReplaceAllUsesWith!");
3993 if (From->getNumValues() == 1) // If possible, use the faster version.
3994 return ReplaceAllUsesWith(SDOperand(From, 0), SDOperand(To, 0),
3997 while (!From->use_empty()) {
3998 SDNode::use_iterator UI = From->use_begin();
3999 SDNode *U = UI->getUser();
4001 // This node is about to morph, remove its old self from the CSE maps.
4002 RemoveNodeFromCSEMaps(U);
4004 for (SDNode::op_iterator I = U->op_begin(), E = U->op_end();
4005 I != E; ++I, ++operandNum)
4006 if (I->getVal() == From) {
4007 From->removeUser(operandNum, U);
4009 To->addUser(operandNum, U);
4012 // Now that we have modified U, add it back to the CSE maps. If it already
4013 // exists there, recursively merge the results together.
4014 if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
4015 ReplaceAllUsesWith(U, Existing, UpdateListener);
4016 // U is now dead. Inform the listener if it exists and delete it.
4018 UpdateListener->NodeDeleted(U, Existing);
4019 DeleteNodeNotInCSEMaps(U);
4021 // If the node doesn't already exist, we updated it. Inform a listener if
4024 UpdateListener->NodeUpdated(U);
4029 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
4030 /// This can cause recursive merging of nodes in the DAG.
4032 /// This version can replace From with any result values. To must match the
4033 /// number and types of values returned by From.
4034 void SelectionDAG::ReplaceAllUsesWith(SDNode *From,
4035 const SDOperand *To,
4036 DAGUpdateListener *UpdateListener) {
4037 if (From->getNumValues() == 1) // Handle the simple case efficiently.
4038 return ReplaceAllUsesWith(SDOperand(From, 0), To[0], UpdateListener);
4040 while (!From->use_empty()) {
4041 SDNode::use_iterator UI = From->use_begin();
4042 SDNode *U = UI->getUser();
4044 // This node is about to morph, remove its old self from the CSE maps.
4045 RemoveNodeFromCSEMaps(U);
4047 for (SDNode::op_iterator I = U->op_begin(), E = U->op_end();
4048 I != E; ++I, ++operandNum)
4049 if (I->getVal() == From) {
4050 const SDOperand &ToOp = To[I->getSDOperand().ResNo];
4051 From->removeUser(operandNum, U);
4054 ToOp.Val->addUser(operandNum, U);
4057 // Now that we have modified U, add it back to the CSE maps. If it already
4058 // exists there, recursively merge the results together.
4059 if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
4060 ReplaceAllUsesWith(U, Existing, UpdateListener);
4061 // U is now dead. Inform the listener if it exists and delete it.
4063 UpdateListener->NodeDeleted(U, Existing);
4064 DeleteNodeNotInCSEMaps(U);
4066 // If the node doesn't already exist, we updated it. Inform a listener if
4069 UpdateListener->NodeUpdated(U);
4075 /// ChainedSetUpdaterListener - This class is a DAGUpdateListener that removes
4076 /// any deleted nodes from the set passed into its constructor and recursively
4077 /// notifies another update listener if specified.
4078 class ChainedSetUpdaterListener :
4079 public SelectionDAG::DAGUpdateListener {
4080 SmallSetVector<SDNode*, 16> &Set;
4081 SelectionDAG::DAGUpdateListener *Chain;
4083 ChainedSetUpdaterListener(SmallSetVector<SDNode*, 16> &set,
4084 SelectionDAG::DAGUpdateListener *chain)
4085 : Set(set), Chain(chain) {}
4087 virtual void NodeDeleted(SDNode *N, SDNode *E) {
4089 if (Chain) Chain->NodeDeleted(N, E);
4091 virtual void NodeUpdated(SDNode *N) {
4092 if (Chain) Chain->NodeUpdated(N);
4097 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
4098 /// uses of other values produced by From.Val alone. The Deleted vector is
4099 /// handled the same way as for ReplaceAllUsesWith.
4100 void SelectionDAG::ReplaceAllUsesOfValueWith(SDOperand From, SDOperand To,
4101 DAGUpdateListener *UpdateListener){
4102 assert(From != To && "Cannot replace a value with itself");
4104 // Handle the simple, trivial, case efficiently.
4105 if (From.Val->getNumValues() == 1) {
4106 ReplaceAllUsesWith(From, To, UpdateListener);
4110 if (From.use_empty()) return;
4112 // Get all of the users of From.Val. We want these in a nice,
4113 // deterministically ordered and uniqued set, so we use a SmallSetVector.
4114 SmallSetVector<SDNode*, 16> Users;
4115 for (SDNode::use_iterator UI = From.Val->use_begin(),
4116 E = From.Val->use_end(); UI != E; ++UI) {
4117 SDNode *User = UI->getUser();
4121 // When one of the recursive merges deletes nodes from the graph, we need to
4122 // make sure that UpdateListener is notified *and* that the node is removed
4123 // from Users if present. CSUL does this.
4124 ChainedSetUpdaterListener CSUL(Users, UpdateListener);
4126 while (!Users.empty()) {
4127 // We know that this user uses some value of From. If it is the right
4128 // value, update it.
4129 SDNode *User = Users.back();
4132 // Scan for an operand that matches From.
4133 SDNode::op_iterator Op = User->op_begin(), E = User->op_end();
4134 for (; Op != E; ++Op)
4135 if (*Op == From) break;
4137 // If there are no matches, the user must use some other result of From.
4138 if (Op == E) continue;
4140 // Okay, we know this user needs to be updated. Remove its old self
4141 // from the CSE maps.
4142 RemoveNodeFromCSEMaps(User);
4144 // Update all operands that match "From" in case there are multiple uses.
4145 for (; Op != E; ++Op) {
4147 From.Val->removeUser(Op-User->op_begin(), User);
4150 To.Val->addUser(Op-User->op_begin(), User);
4154 // Now that we have modified User, add it back to the CSE maps. If it
4155 // already exists there, recursively merge the results together.
4156 SDNode *Existing = AddNonLeafNodeToCSEMaps(User);
4158 if (UpdateListener) UpdateListener->NodeUpdated(User);
4159 continue; // Continue on to next user.
4162 // If there was already an existing matching node, use ReplaceAllUsesWith
4163 // to replace the dead one with the existing one. This can cause
4164 // recursive merging of other unrelated nodes down the line. The merging
4165 // can cause deletion of nodes that used the old value. To handle this, we
4166 // use CSUL to remove them from the Users set.
4167 ReplaceAllUsesWith(User, Existing, &CSUL);
4169 // User is now dead. Notify a listener if present.
4170 if (UpdateListener) UpdateListener->NodeDeleted(User, Existing);
4171 DeleteNodeNotInCSEMaps(User);
4175 /// AssignNodeIds - Assign a unique node id for each node in the DAG based on
4176 /// their allnodes order. It returns the maximum id.
4177 unsigned SelectionDAG::AssignNodeIds() {
4179 for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I){
4186 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
4187 /// based on their topological order. It returns the maximum id and a vector
4188 /// of the SDNodes* in assigned order by reference.
4189 unsigned SelectionDAG::AssignTopologicalOrder(std::vector<SDNode*> &TopOrder) {
4190 unsigned DAGSize = AllNodes.size();
4191 std::vector<unsigned> InDegree(DAGSize);
4192 std::vector<SDNode*> Sources;
4194 // Use a two pass approach to avoid using a std::map which is slow.
4196 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ++I){
4199 unsigned Degree = N->use_size();
4200 InDegree[N->getNodeId()] = Degree;
4202 Sources.push_back(N);
4206 while (!Sources.empty()) {
4207 SDNode *N = Sources.back();
4209 TopOrder.push_back(N);
4210 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
4211 SDNode *P = I->getVal();
4212 unsigned Degree = --InDegree[P->getNodeId()];
4214 Sources.push_back(P);
4218 // Second pass, assign the actual topological order as node ids.
4220 for (std::vector<SDNode*>::iterator TI = TopOrder.begin(),TE = TopOrder.end();
4222 (*TI)->setNodeId(Id++);
4229 //===----------------------------------------------------------------------===//
4231 //===----------------------------------------------------------------------===//
4233 // Out-of-line virtual method to give class a home.
4234 void SDNode::ANCHOR() {}
4235 void UnarySDNode::ANCHOR() {}
4236 void BinarySDNode::ANCHOR() {}
4237 void TernarySDNode::ANCHOR() {}
4238 void HandleSDNode::ANCHOR() {}
4239 void ConstantSDNode::ANCHOR() {}
4240 void ConstantFPSDNode::ANCHOR() {}
4241 void GlobalAddressSDNode::ANCHOR() {}
4242 void FrameIndexSDNode::ANCHOR() {}
4243 void JumpTableSDNode::ANCHOR() {}
4244 void ConstantPoolSDNode::ANCHOR() {}
4245 void BasicBlockSDNode::ANCHOR() {}
4246 void SrcValueSDNode::ANCHOR() {}
4247 void MemOperandSDNode::ANCHOR() {}
4248 void RegisterSDNode::ANCHOR() {}
4249 void DbgStopPointSDNode::ANCHOR() {}
4250 void LabelSDNode::ANCHOR() {}
4251 void ExternalSymbolSDNode::ANCHOR() {}
4252 void CondCodeSDNode::ANCHOR() {}
4253 void ARG_FLAGSSDNode::ANCHOR() {}
4254 void VTSDNode::ANCHOR() {}
4255 void MemSDNode::ANCHOR() {}
4256 void LoadSDNode::ANCHOR() {}
4257 void StoreSDNode::ANCHOR() {}
4258 void AtomicSDNode::ANCHOR() {}
4260 HandleSDNode::~HandleSDNode() {
4264 GlobalAddressSDNode::GlobalAddressSDNode(bool isTarget, const GlobalValue *GA,
4266 : SDNode(isa<GlobalVariable>(GA) &&
4267 cast<GlobalVariable>(GA)->isThreadLocal() ?
4269 (isTarget ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress) :
4271 (isTarget ? ISD::TargetGlobalAddress : ISD::GlobalAddress),
4272 getSDVTList(VT)), Offset(o) {
4273 TheGlobal = const_cast<GlobalValue*>(GA);
4276 /// getMemOperand - Return a MachineMemOperand object describing the memory
4277 /// reference performed by this atomic.
4278 MachineMemOperand AtomicSDNode::getMemOperand() const {
4279 int Size = (getValueType(0).getSizeInBits() + 7) >> 3;
4280 int Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
4281 if (isVolatile()) Flags |= MachineMemOperand::MOVolatile;
4283 // Check if the atomic references a frame index
4284 const FrameIndexSDNode *FI =
4285 dyn_cast<const FrameIndexSDNode>(getBasePtr().Val);
4286 if (!getSrcValue() && FI)
4287 return MachineMemOperand(PseudoSourceValue::getFixedStack(), Flags,
4288 FI->getIndex(), Size, getAlignment());
4290 return MachineMemOperand(getSrcValue(), Flags, getSrcValueOffset(),
4291 Size, getAlignment());
4294 /// getMemOperand - Return a MachineMemOperand object describing the memory
4295 /// reference performed by this load or store.
4296 MachineMemOperand LSBaseSDNode::getMemOperand() const {
4297 int Size = (getMemoryVT().getSizeInBits() + 7) >> 3;
4299 getOpcode() == ISD::LOAD ? MachineMemOperand::MOLoad :
4300 MachineMemOperand::MOStore;
4301 if (isVolatile()) Flags |= MachineMemOperand::MOVolatile;
4303 // Check if the load references a frame index, and does not have
4305 const FrameIndexSDNode *FI =
4306 dyn_cast<const FrameIndexSDNode>(getBasePtr().Val);
4307 if (!getSrcValue() && FI)
4308 return MachineMemOperand(PseudoSourceValue::getFixedStack(), Flags,
4309 FI->getIndex(), Size, getAlignment());
4311 return MachineMemOperand(getSrcValue(), Flags,
4312 getSrcValueOffset(), Size, getAlignment());
4315 /// Profile - Gather unique data for the node.
4317 void SDNode::Profile(FoldingSetNodeID &ID) {
4318 AddNodeIDNode(ID, this);
4321 /// getValueTypeList - Return a pointer to the specified value type.
4323 const MVT *SDNode::getValueTypeList(MVT VT) {
4324 if (VT.isExtended()) {
4325 static std::set<MVT, MVT::compareRawBits> EVTs;
4326 return &(*EVTs.insert(VT).first);
4328 static MVT VTs[MVT::LAST_VALUETYPE];
4329 VTs[VT.getSimpleVT()] = VT;
4330 return &VTs[VT.getSimpleVT()];
4334 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
4335 /// indicated value. This method ignores uses of other values defined by this
4337 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
4338 assert(Value < getNumValues() && "Bad value!");
4340 // If there is only one value, this is easy.
4341 if (getNumValues() == 1)
4342 return use_size() == NUses;
4343 if (use_size() < NUses) return false;
4345 SDOperand TheValue(const_cast<SDNode *>(this), Value);
4347 SmallPtrSet<SDNode*, 32> UsersHandled;
4349 // TODO: Only iterate over uses of a given value of the node
4350 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
4351 if (*UI == TheValue) {
4358 // Found exactly the right number of uses?
4363 /// hasAnyUseOfValue - Return true if there are any use of the indicated
4364 /// value. This method ignores uses of other values defined by this operation.
4365 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
4366 assert(Value < getNumValues() && "Bad value!");
4368 if (use_empty()) return false;
4370 SDOperand TheValue(const_cast<SDNode *>(this), Value);
4372 SmallPtrSet<SDNode*, 32> UsersHandled;
4374 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
4375 SDNode *User = UI->getUser();
4376 if (User->getNumOperands() == 1 ||
4377 UsersHandled.insert(User)) // First time we've seen this?
4378 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
4379 if (User->getOperand(i) == TheValue) {
4388 /// isOnlyUseOf - Return true if this node is the only use of N.
4390 bool SDNode::isOnlyUseOf(SDNode *N) const {
4392 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
4393 SDNode *User = I->getUser();
4403 /// isOperand - Return true if this node is an operand of N.
4405 bool SDOperand::isOperandOf(SDNode *N) const {
4406 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4407 if (*this == N->getOperand(i))
4412 bool SDNode::isOperandOf(SDNode *N) const {
4413 for (unsigned i = 0, e = N->NumOperands; i != e; ++i)
4414 if (this == N->OperandList[i].getVal())
4419 /// reachesChainWithoutSideEffects - Return true if this operand (which must
4420 /// be a chain) reaches the specified operand without crossing any
4421 /// side-effecting instructions. In practice, this looks through token
4422 /// factors and non-volatile loads. In order to remain efficient, this only
4423 /// looks a couple of nodes in, it does not do an exhaustive search.
4424 bool SDOperand::reachesChainWithoutSideEffects(SDOperand Dest,
4425 unsigned Depth) const {
4426 if (*this == Dest) return true;
4428 // Don't search too deeply, we just want to be able to see through
4429 // TokenFactor's etc.
4430 if (Depth == 0) return false;
4432 // If this is a token factor, all inputs to the TF happen in parallel. If any
4433 // of the operands of the TF reach dest, then we can do the xform.
4434 if (getOpcode() == ISD::TokenFactor) {
4435 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
4436 if (getOperand(i).reachesChainWithoutSideEffects(Dest, Depth-1))
4441 // Loads don't have side effects, look through them.
4442 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
4443 if (!Ld->isVolatile())
4444 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
4450 static void findPredecessor(SDNode *N, const SDNode *P, bool &found,
4451 SmallPtrSet<SDNode *, 32> &Visited) {
4452 if (found || !Visited.insert(N))
4455 for (unsigned i = 0, e = N->getNumOperands(); !found && i != e; ++i) {
4456 SDNode *Op = N->getOperand(i).Val;
4461 findPredecessor(Op, P, found, Visited);
4465 /// isPredecessorOf - Return true if this node is a predecessor of N. This node
4466 /// is either an operand of N or it can be reached by recursively traversing
4467 /// up the operands.
4468 /// NOTE: this is an expensive method. Use it carefully.
4469 bool SDNode::isPredecessorOf(SDNode *N) const {
4470 SmallPtrSet<SDNode *, 32> Visited;
4472 findPredecessor(N, this, found, Visited);
4476 uint64_t SDNode::getConstantOperandVal(unsigned Num) const {
4477 assert(Num < NumOperands && "Invalid child # of SDNode!");
4478 return cast<ConstantSDNode>(OperandList[Num])->getValue();
4481 std::string SDNode::getOperationName(const SelectionDAG *G) const {
4482 switch (getOpcode()) {
4484 if (getOpcode() < ISD::BUILTIN_OP_END)
4485 return "<<Unknown DAG Node>>";
4488 if (const TargetInstrInfo *TII = G->getTarget().getInstrInfo())
4489 if (getOpcode()-ISD::BUILTIN_OP_END < TII->getNumOpcodes())
4490 return TII->get(getOpcode()-ISD::BUILTIN_OP_END).getName();
4492 TargetLowering &TLI = G->getTargetLoweringInfo();
4494 TLI.getTargetNodeName(getOpcode());
4495 if (Name) return Name;
4498 return "<<Unknown Target Node>>";
4501 case ISD::PREFETCH: return "Prefetch";
4502 case ISD::MEMBARRIER: return "MemBarrier";
4503 case ISD::ATOMIC_CMP_SWAP: return "AtomicCmpSwap";
4504 case ISD::ATOMIC_LOAD_ADD: return "AtomicLoadAdd";
4505 case ISD::ATOMIC_LOAD_SUB: return "AtomicLoadSub";
4506 case ISD::ATOMIC_LOAD_AND: return "AtomicLoadAnd";
4507 case ISD::ATOMIC_LOAD_OR: return "AtomicLoadOr";
4508 case ISD::ATOMIC_LOAD_XOR: return "AtomicLoadXor";
4509 case ISD::ATOMIC_LOAD_NAND: return "AtomicLoadNand";
4510 case ISD::ATOMIC_LOAD_MIN: return "AtomicLoadMin";
4511 case ISD::ATOMIC_LOAD_MAX: return "AtomicLoadMax";
4512 case ISD::ATOMIC_LOAD_UMIN: return "AtomicLoadUMin";
4513 case ISD::ATOMIC_LOAD_UMAX: return "AtomicLoadUMax";
4514 case ISD::ATOMIC_SWAP: return "AtomicSWAP";
4515 case ISD::PCMARKER: return "PCMarker";
4516 case ISD::READCYCLECOUNTER: return "ReadCycleCounter";
4517 case ISD::SRCVALUE: return "SrcValue";
4518 case ISD::MEMOPERAND: return "MemOperand";
4519 case ISD::EntryToken: return "EntryToken";
4520 case ISD::TokenFactor: return "TokenFactor";
4521 case ISD::AssertSext: return "AssertSext";
4522 case ISD::AssertZext: return "AssertZext";
4524 case ISD::BasicBlock: return "BasicBlock";
4525 case ISD::ARG_FLAGS: return "ArgFlags";
4526 case ISD::VALUETYPE: return "ValueType";
4527 case ISD::Register: return "Register";
4529 case ISD::Constant: return "Constant";
4530 case ISD::ConstantFP: return "ConstantFP";
4531 case ISD::GlobalAddress: return "GlobalAddress";
4532 case ISD::GlobalTLSAddress: return "GlobalTLSAddress";
4533 case ISD::FrameIndex: return "FrameIndex";
4534 case ISD::JumpTable: return "JumpTable";
4535 case ISD::GLOBAL_OFFSET_TABLE: return "GLOBAL_OFFSET_TABLE";
4536 case ISD::RETURNADDR: return "RETURNADDR";
4537 case ISD::FRAMEADDR: return "FRAMEADDR";
4538 case ISD::FRAME_TO_ARGS_OFFSET: return "FRAME_TO_ARGS_OFFSET";
4539 case ISD::EXCEPTIONADDR: return "EXCEPTIONADDR";
4540 case ISD::EHSELECTION: return "EHSELECTION";
4541 case ISD::EH_RETURN: return "EH_RETURN";
4542 case ISD::ConstantPool: return "ConstantPool";
4543 case ISD::ExternalSymbol: return "ExternalSymbol";
4544 case ISD::INTRINSIC_WO_CHAIN: {
4545 unsigned IID = cast<ConstantSDNode>(getOperand(0))->getValue();
4546 return Intrinsic::getName((Intrinsic::ID)IID);
4548 case ISD::INTRINSIC_VOID:
4549 case ISD::INTRINSIC_W_CHAIN: {
4550 unsigned IID = cast<ConstantSDNode>(getOperand(1))->getValue();
4551 return Intrinsic::getName((Intrinsic::ID)IID);
4554 case ISD::BUILD_VECTOR: return "BUILD_VECTOR";
4555 case ISD::TargetConstant: return "TargetConstant";
4556 case ISD::TargetConstantFP:return "TargetConstantFP";
4557 case ISD::TargetGlobalAddress: return "TargetGlobalAddress";
4558 case ISD::TargetGlobalTLSAddress: return "TargetGlobalTLSAddress";
4559 case ISD::TargetFrameIndex: return "TargetFrameIndex";
4560 case ISD::TargetJumpTable: return "TargetJumpTable";
4561 case ISD::TargetConstantPool: return "TargetConstantPool";
4562 case ISD::TargetExternalSymbol: return "TargetExternalSymbol";
4564 case ISD::CopyToReg: return "CopyToReg";
4565 case ISD::CopyFromReg: return "CopyFromReg";
4566 case ISD::UNDEF: return "undef";
4567 case ISD::MERGE_VALUES: return "merge_values";
4568 case ISD::INLINEASM: return "inlineasm";
4569 case ISD::DBG_LABEL: return "dbg_label";
4570 case ISD::EH_LABEL: return "eh_label";
4571 case ISD::DECLARE: return "declare";
4572 case ISD::HANDLENODE: return "handlenode";
4573 case ISD::FORMAL_ARGUMENTS: return "formal_arguments";
4574 case ISD::CALL: return "call";
4577 case ISD::FABS: return "fabs";
4578 case ISD::FNEG: return "fneg";
4579 case ISD::FSQRT: return "fsqrt";
4580 case ISD::FSIN: return "fsin";
4581 case ISD::FCOS: return "fcos";
4582 case ISD::FPOWI: return "fpowi";
4583 case ISD::FPOW: return "fpow";
4586 case ISD::ADD: return "add";
4587 case ISD::SUB: return "sub";
4588 case ISD::MUL: return "mul";
4589 case ISD::MULHU: return "mulhu";
4590 case ISD::MULHS: return "mulhs";
4591 case ISD::SDIV: return "sdiv";
4592 case ISD::UDIV: return "udiv";
4593 case ISD::SREM: return "srem";
4594 case ISD::UREM: return "urem";
4595 case ISD::SMUL_LOHI: return "smul_lohi";
4596 case ISD::UMUL_LOHI: return "umul_lohi";
4597 case ISD::SDIVREM: return "sdivrem";
4598 case ISD::UDIVREM: return "divrem";
4599 case ISD::AND: return "and";
4600 case ISD::OR: return "or";
4601 case ISD::XOR: return "xor";
4602 case ISD::SHL: return "shl";
4603 case ISD::SRA: return "sra";
4604 case ISD::SRL: return "srl";
4605 case ISD::ROTL: return "rotl";
4606 case ISD::ROTR: return "rotr";
4607 case ISD::FADD: return "fadd";
4608 case ISD::FSUB: return "fsub";
4609 case ISD::FMUL: return "fmul";
4610 case ISD::FDIV: return "fdiv";
4611 case ISD::FREM: return "frem";
4612 case ISD::FCOPYSIGN: return "fcopysign";
4613 case ISD::FGETSIGN: return "fgetsign";
4615 case ISD::SETCC: return "setcc";
4616 case ISD::VSETCC: return "vsetcc";
4617 case ISD::SELECT: return "select";
4618 case ISD::SELECT_CC: return "select_cc";
4619 case ISD::INSERT_VECTOR_ELT: return "insert_vector_elt";
4620 case ISD::EXTRACT_VECTOR_ELT: return "extract_vector_elt";
4621 case ISD::CONCAT_VECTORS: return "concat_vectors";
4622 case ISD::EXTRACT_SUBVECTOR: return "extract_subvector";
4623 case ISD::SCALAR_TO_VECTOR: return "scalar_to_vector";
4624 case ISD::VECTOR_SHUFFLE: return "vector_shuffle";
4625 case ISD::CARRY_FALSE: return "carry_false";
4626 case ISD::ADDC: return "addc";
4627 case ISD::ADDE: return "adde";
4628 case ISD::SUBC: return "subc";
4629 case ISD::SUBE: return "sube";
4630 case ISD::SHL_PARTS: return "shl_parts";
4631 case ISD::SRA_PARTS: return "sra_parts";
4632 case ISD::SRL_PARTS: return "srl_parts";
4634 case ISD::EXTRACT_SUBREG: return "extract_subreg";
4635 case ISD::INSERT_SUBREG: return "insert_subreg";
4637 // Conversion operators.
4638 case ISD::SIGN_EXTEND: return "sign_extend";
4639 case ISD::ZERO_EXTEND: return "zero_extend";
4640 case ISD::ANY_EXTEND: return "any_extend";
4641 case ISD::SIGN_EXTEND_INREG: return "sign_extend_inreg";
4642 case ISD::TRUNCATE: return "truncate";
4643 case ISD::FP_ROUND: return "fp_round";
4644 case ISD::FLT_ROUNDS_: return "flt_rounds";
4645 case ISD::FP_ROUND_INREG: return "fp_round_inreg";
4646 case ISD::FP_EXTEND: return "fp_extend";
4648 case ISD::SINT_TO_FP: return "sint_to_fp";
4649 case ISD::UINT_TO_FP: return "uint_to_fp";
4650 case ISD::FP_TO_SINT: return "fp_to_sint";
4651 case ISD::FP_TO_UINT: return "fp_to_uint";
4652 case ISD::BIT_CONVERT: return "bit_convert";
4654 // Control flow instructions
4655 case ISD::BR: return "br";
4656 case ISD::BRIND: return "brind";
4657 case ISD::BR_JT: return "br_jt";
4658 case ISD::BRCOND: return "brcond";
4659 case ISD::BR_CC: return "br_cc";
4660 case ISD::RET: return "ret";
4661 case ISD::CALLSEQ_START: return "callseq_start";
4662 case ISD::CALLSEQ_END: return "callseq_end";
4665 case ISD::LOAD: return "load";
4666 case ISD::STORE: return "store";
4667 case ISD::VAARG: return "vaarg";
4668 case ISD::VACOPY: return "vacopy";
4669 case ISD::VAEND: return "vaend";
4670 case ISD::VASTART: return "vastart";
4671 case ISD::DYNAMIC_STACKALLOC: return "dynamic_stackalloc";
4672 case ISD::EXTRACT_ELEMENT: return "extract_element";
4673 case ISD::BUILD_PAIR: return "build_pair";
4674 case ISD::STACKSAVE: return "stacksave";
4675 case ISD::STACKRESTORE: return "stackrestore";
4676 case ISD::TRAP: return "trap";
4679 case ISD::BSWAP: return "bswap";
4680 case ISD::CTPOP: return "ctpop";
4681 case ISD::CTTZ: return "cttz";
4682 case ISD::CTLZ: return "ctlz";
4685 case ISD::DBG_STOPPOINT: return "dbg_stoppoint";
4686 case ISD::DEBUG_LOC: return "debug_loc";
4689 case ISD::TRAMPOLINE: return "trampoline";
4692 switch (cast<CondCodeSDNode>(this)->get()) {
4693 default: assert(0 && "Unknown setcc condition!");
4694 case ISD::SETOEQ: return "setoeq";
4695 case ISD::SETOGT: return "setogt";
4696 case ISD::SETOGE: return "setoge";
4697 case ISD::SETOLT: return "setolt";
4698 case ISD::SETOLE: return "setole";
4699 case ISD::SETONE: return "setone";
4701 case ISD::SETO: return "seto";
4702 case ISD::SETUO: return "setuo";
4703 case ISD::SETUEQ: return "setue";
4704 case ISD::SETUGT: return "setugt";
4705 case ISD::SETUGE: return "setuge";
4706 case ISD::SETULT: return "setult";
4707 case ISD::SETULE: return "setule";
4708 case ISD::SETUNE: return "setune";
4710 case ISD::SETEQ: return "seteq";
4711 case ISD::SETGT: return "setgt";
4712 case ISD::SETGE: return "setge";
4713 case ISD::SETLT: return "setlt";
4714 case ISD::SETLE: return "setle";
4715 case ISD::SETNE: return "setne";
4720 const char *SDNode::getIndexedModeName(ISD::MemIndexedMode AM) {
4729 return "<post-inc>";
4731 return "<post-dec>";
4735 std::string ISD::ArgFlagsTy::getArgFlagsString() {
4736 std::string S = "< ";
4750 if (getByValAlign())
4751 S += "byval-align:" + utostr(getByValAlign()) + " ";
4753 S += "orig-align:" + utostr(getOrigAlign()) + " ";
4755 S += "byval-size:" + utostr(getByValSize()) + " ";
4759 void SDNode::dump() const { dump(0); }
4760 void SDNode::dump(const SelectionDAG *G) const {
4761 cerr << (void*)this << ": ";
4763 for (unsigned i = 0, e = getNumValues(); i != e; ++i) {
4765 if (getValueType(i) == MVT::Other)
4768 cerr << getValueType(i).getMVTString();
4770 cerr << " = " << getOperationName(G);
4773 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
4774 if (i) cerr << ", ";
4775 cerr << (void*)getOperand(i).Val;
4776 if (unsigned RN = getOperand(i).ResNo)
4780 if (!isTargetOpcode() && getOpcode() == ISD::VECTOR_SHUFFLE) {
4781 SDNode *Mask = getOperand(2).Val;
4783 for (unsigned i = 0, e = Mask->getNumOperands(); i != e; ++i) {
4785 if (Mask->getOperand(i).getOpcode() == ISD::UNDEF)
4788 cerr << cast<ConstantSDNode>(Mask->getOperand(i))->getValue();
4793 if (const ConstantSDNode *CSDN = dyn_cast<ConstantSDNode>(this)) {
4794 cerr << "<" << CSDN->getValue() << ">";
4795 } else if (const ConstantFPSDNode *CSDN = dyn_cast<ConstantFPSDNode>(this)) {
4796 if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEsingle)
4797 cerr << "<" << CSDN->getValueAPF().convertToFloat() << ">";
4798 else if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEdouble)
4799 cerr << "<" << CSDN->getValueAPF().convertToDouble() << ">";
4801 cerr << "<APFloat(";
4802 CSDN->getValueAPF().convertToAPInt().dump();
4805 } else if (const GlobalAddressSDNode *GADN =
4806 dyn_cast<GlobalAddressSDNode>(this)) {
4807 int offset = GADN->getOffset();
4809 WriteAsOperand(*cerr.stream(), GADN->getGlobal()) << ">";
4811 cerr << " + " << offset;
4813 cerr << " " << offset;
4814 } else if (const FrameIndexSDNode *FIDN = dyn_cast<FrameIndexSDNode>(this)) {
4815 cerr << "<" << FIDN->getIndex() << ">";
4816 } else if (const JumpTableSDNode *JTDN = dyn_cast<JumpTableSDNode>(this)) {
4817 cerr << "<" << JTDN->getIndex() << ">";
4818 } else if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(this)){
4819 int offset = CP->getOffset();
4820 if (CP->isMachineConstantPoolEntry())
4821 cerr << "<" << *CP->getMachineCPVal() << ">";
4823 cerr << "<" << *CP->getConstVal() << ">";
4825 cerr << " + " << offset;
4827 cerr << " " << offset;
4828 } else if (const BasicBlockSDNode *BBDN = dyn_cast<BasicBlockSDNode>(this)) {
4830 const Value *LBB = (const Value*)BBDN->getBasicBlock()->getBasicBlock();
4832 cerr << LBB->getName() << " ";
4833 cerr << (const void*)BBDN->getBasicBlock() << ">";
4834 } else if (const RegisterSDNode *R = dyn_cast<RegisterSDNode>(this)) {
4835 if (G && R->getReg() &&
4836 TargetRegisterInfo::isPhysicalRegister(R->getReg())) {
4837 cerr << " " << G->getTarget().getRegisterInfo()->getName(R->getReg());
4839 cerr << " #" << R->getReg();
4841 } else if (const ExternalSymbolSDNode *ES =
4842 dyn_cast<ExternalSymbolSDNode>(this)) {
4843 cerr << "'" << ES->getSymbol() << "'";
4844 } else if (const SrcValueSDNode *M = dyn_cast<SrcValueSDNode>(this)) {
4846 cerr << "<" << M->getValue() << ">";
4849 } else if (const MemOperandSDNode *M = dyn_cast<MemOperandSDNode>(this)) {
4850 if (M->MO.getValue())
4851 cerr << "<" << M->MO.getValue() << ":" << M->MO.getOffset() << ">";
4853 cerr << "<null:" << M->MO.getOffset() << ">";
4854 } else if (const ARG_FLAGSSDNode *N = dyn_cast<ARG_FLAGSSDNode>(this)) {
4855 cerr << N->getArgFlags().getArgFlagsString();
4856 } else if (const VTSDNode *N = dyn_cast<VTSDNode>(this)) {
4857 cerr << ":" << N->getVT().getMVTString();
4859 else if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(this)) {
4860 const Value *SrcValue = LD->getSrcValue();
4861 int SrcOffset = LD->getSrcValueOffset();
4867 cerr << ":" << SrcOffset << ">";
4870 switch (LD->getExtensionType()) {
4871 default: doExt = false; break;
4873 cerr << " <anyext ";
4883 cerr << LD->getMemoryVT().getMVTString() << ">";
4885 const char *AM = getIndexedModeName(LD->getAddressingMode());
4888 if (LD->isVolatile())
4889 cerr << " <volatile>";
4890 cerr << " alignment=" << LD->getAlignment();
4891 } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(this)) {
4892 const Value *SrcValue = ST->getSrcValue();
4893 int SrcOffset = ST->getSrcValueOffset();
4899 cerr << ":" << SrcOffset << ">";
4901 if (ST->isTruncatingStore())
4903 << ST->getMemoryVT().getMVTString() << ">";
4905 const char *AM = getIndexedModeName(ST->getAddressingMode());
4908 if (ST->isVolatile())
4909 cerr << " <volatile>";
4910 cerr << " alignment=" << ST->getAlignment();
4911 } else if (const AtomicSDNode* AT = dyn_cast<AtomicSDNode>(this)) {
4912 const Value *SrcValue = AT->getSrcValue();
4913 int SrcOffset = AT->getSrcValueOffset();
4919 cerr << ":" << SrcOffset << ">";
4920 if (AT->isVolatile())
4921 cerr << " <volatile>";
4922 cerr << " alignment=" << AT->getAlignment();
4926 static void DumpNodes(const SDNode *N, unsigned indent, const SelectionDAG *G) {
4927 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4928 if (N->getOperand(i).Val->hasOneUse())
4929 DumpNodes(N->getOperand(i).Val, indent+2, G);
4931 cerr << "\n" << std::string(indent+2, ' ')
4932 << (void*)N->getOperand(i).Val << ": <multiple use>";
4935 cerr << "\n" << std::string(indent, ' ');
4939 void SelectionDAG::dump() const {
4940 cerr << "SelectionDAG has " << AllNodes.size() << " nodes:";
4941 std::vector<const SDNode*> Nodes;
4942 for (allnodes_const_iterator I = allnodes_begin(), E = allnodes_end();
4946 std::sort(Nodes.begin(), Nodes.end());
4948 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
4949 if (!Nodes[i]->hasOneUse() && Nodes[i] != getRoot().Val)
4950 DumpNodes(Nodes[i], 2, this);
4953 if (getRoot().Val) DumpNodes(getRoot().Val, 2, this);
4958 const Type *ConstantPoolSDNode::getType() const {
4959 if (isMachineConstantPoolEntry())
4960 return Val.MachineCPVal->getType();
4961 return Val.ConstVal->getType();