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 SDValue 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 SDValue 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 SDValue 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->isMachineOpcode() &&
201 N->getMachineOpcode() == 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 SDValue *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->getVal());
339 ID.AddInteger(Ops->getSDValue().ResNo);
343 static void AddNodeIDNode(FoldingSetNodeID &ID,
344 unsigned short OpC, SDVTList VTList,
345 const SDValue *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());
399 ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
401 case ISD::MEMOPERAND: {
402 const MachineMemOperand &MO = cast<MemOperandSDNode>(N)->MO;
403 ID.AddPointer(MO.getValue());
404 ID.AddInteger(MO.getFlags());
405 ID.AddInteger(MO.getOffset());
406 ID.AddInteger(MO.getSize());
407 ID.AddInteger(MO.getAlignment());
410 case ISD::FrameIndex:
411 case ISD::TargetFrameIndex:
412 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
415 case ISD::TargetJumpTable:
416 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
418 case ISD::ConstantPool:
419 case ISD::TargetConstantPool: {
420 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
421 ID.AddInteger(CP->getAlignment());
422 ID.AddInteger(CP->getOffset());
423 if (CP->isMachineConstantPoolEntry())
424 CP->getMachineCPVal()->AddSelectionDAGCSEId(ID);
426 ID.AddPointer(CP->getConstVal());
430 LoadSDNode *LD = cast<LoadSDNode>(N);
431 ID.AddInteger(LD->getAddressingMode());
432 ID.AddInteger(LD->getExtensionType());
433 ID.AddInteger(LD->getMemoryVT().getRawBits());
434 ID.AddInteger(LD->getAlignment());
435 ID.AddInteger(LD->isVolatile());
439 StoreSDNode *ST = cast<StoreSDNode>(N);
440 ID.AddInteger(ST->getAddressingMode());
441 ID.AddInteger(ST->isTruncatingStore());
442 ID.AddInteger(ST->getMemoryVT().getRawBits());
443 ID.AddInteger(ST->getAlignment());
444 ID.AddInteger(ST->isVolatile());
447 case ISD::ATOMIC_CMP_SWAP:
448 case ISD::ATOMIC_LOAD_ADD:
449 case ISD::ATOMIC_SWAP:
450 case ISD::ATOMIC_LOAD_SUB:
451 case ISD::ATOMIC_LOAD_AND:
452 case ISD::ATOMIC_LOAD_OR:
453 case ISD::ATOMIC_LOAD_XOR:
454 case ISD::ATOMIC_LOAD_NAND:
455 case ISD::ATOMIC_LOAD_MIN:
456 case ISD::ATOMIC_LOAD_MAX:
457 case ISD::ATOMIC_LOAD_UMIN:
458 case ISD::ATOMIC_LOAD_UMAX: {
459 AtomicSDNode *AT = cast<AtomicSDNode>(N);
460 ID.AddInteger(AT->getAlignment());
461 ID.AddInteger(AT->isVolatile());
464 } // end switch (N->getOpcode())
467 //===----------------------------------------------------------------------===//
468 // SelectionDAG Class
469 //===----------------------------------------------------------------------===//
471 inline alist_traits<SDNode, LargestSDNode>::AllocatorType &
472 SelectionDAG::getAllocator() {
473 return AllNodes.getTraits().Allocator;
476 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
478 void SelectionDAG::RemoveDeadNodes() {
479 // Create a dummy node (which is not added to allnodes), that adds a reference
480 // to the root node, preventing it from being deleted.
481 HandleSDNode Dummy(getRoot());
483 SmallVector<SDNode*, 128> DeadNodes;
485 // Add all obviously-dead nodes to the DeadNodes worklist.
486 for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I)
488 DeadNodes.push_back(I);
490 RemoveDeadNodes(DeadNodes);
492 // If the root changed (e.g. it was a dead load, update the root).
493 setRoot(Dummy.getValue());
496 /// RemoveDeadNodes - This method deletes the unreachable nodes in the
497 /// given list, and any nodes that become unreachable as a result.
498 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes,
499 DAGUpdateListener *UpdateListener) {
501 // Process the worklist, deleting the nodes and adding their uses to the
503 while (!DeadNodes.empty()) {
504 SDNode *N = DeadNodes.back();
505 DeadNodes.pop_back();
508 UpdateListener->NodeDeleted(N, 0);
510 // Take the node out of the appropriate CSE map.
511 RemoveNodeFromCSEMaps(N);
513 // Next, brutally remove the operand list. This is safe to do, as there are
514 // no cycles in the graph.
515 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
516 SDNode *Operand = I->getVal();
517 Operand->removeUser(std::distance(N->op_begin(), I), N);
519 // Now that we removed this operand, see if there are no uses of it left.
520 if (Operand->use_empty())
521 DeadNodes.push_back(Operand);
523 if (N->OperandsNeedDelete) {
524 delete[] N->OperandList;
529 // Finally, remove N itself.
534 void SelectionDAG::RemoveDeadNode(SDNode *N, DAGUpdateListener *UpdateListener){
535 SmallVector<SDNode*, 16> DeadNodes(1, 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 // Drop all of the operands and decrement used nodes use counts.
553 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I)
554 I->getVal()->removeUser(std::distance(N->op_begin(), I), N);
555 if (N->OperandsNeedDelete) {
556 delete[] N->OperandList;
564 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
565 /// correspond to it. This is useful when we're about to delete or repurpose
566 /// the node. We don't want future request for structurally identical nodes
567 /// to return N anymore.
568 void SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
570 switch (N->getOpcode()) {
571 case ISD::HANDLENODE: return; // noop.
573 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
574 "Cond code doesn't exist!");
575 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != 0;
576 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = 0;
578 case ISD::ExternalSymbol:
579 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
581 case ISD::TargetExternalSymbol:
583 TargetExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
585 case ISD::VALUETYPE: {
586 MVT VT = cast<VTSDNode>(N)->getVT();
587 if (VT.isExtended()) {
588 Erased = ExtendedValueTypeNodes.erase(VT);
590 Erased = ValueTypeNodes[VT.getSimpleVT()] != 0;
591 ValueTypeNodes[VT.getSimpleVT()] = 0;
596 // Remove it from the CSE Map.
597 Erased = CSEMap.RemoveNode(N);
601 // Verify that the node was actually in one of the CSE maps, unless it has a
602 // flag result (which cannot be CSE'd) or is one of the special cases that are
603 // not subject to CSE.
604 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Flag &&
605 !N->isTargetOpcode() &&
606 N->getOpcode() != ISD::DBG_LABEL &&
607 N->getOpcode() != ISD::DBG_STOPPOINT &&
608 N->getOpcode() != ISD::EH_LABEL &&
609 N->getOpcode() != ISD::DECLARE) {
612 assert(0 && "Node is not in map!");
617 /// AddNonLeafNodeToCSEMaps - Add the specified node back to the CSE maps. It
618 /// has been taken out and modified in some way. If the specified node already
619 /// exists in the CSE maps, do not modify the maps, but return the existing node
620 /// instead. If it doesn't exist, add it and return null.
622 SDNode *SelectionDAG::AddNonLeafNodeToCSEMaps(SDNode *N) {
623 assert(N->getNumOperands() && "This is a leaf node!");
625 if (N->getValueType(0) == MVT::Flag)
626 return 0; // Never CSE anything that produces a flag.
628 switch (N->getOpcode()) {
630 case ISD::HANDLENODE:
632 case ISD::DBG_STOPPOINT:
635 return 0; // Never add these nodes.
638 // Check that remaining values produced are not flags.
639 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
640 if (N->getValueType(i) == MVT::Flag)
641 return 0; // Never CSE anything that produces a flag.
643 SDNode *New = CSEMap.GetOrInsertNode(N);
644 if (New != N) return New; // Node already existed.
648 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
649 /// were replaced with those specified. If this node is never memoized,
650 /// return null, otherwise return a pointer to the slot it would take. If a
651 /// node already exists with these operands, the slot will be non-null.
652 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
654 if (N->getValueType(0) == MVT::Flag)
655 return 0; // Never CSE anything that produces a flag.
657 switch (N->getOpcode()) {
659 case ISD::HANDLENODE:
661 case ISD::DBG_STOPPOINT:
663 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 SDValue Ops[] = { Op };
673 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 1);
674 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
677 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
678 /// were replaced with those specified. If this node is never memoized,
679 /// return null, otherwise return a pointer to the slot it would take. If a
680 /// node already exists with these operands, the slot will be non-null.
681 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
682 SDValue Op1, SDValue Op2,
684 if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
686 // Check that remaining values produced are not flags.
687 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
688 if (N->getValueType(i) == MVT::Flag)
689 return 0; // Never CSE anything that produces a flag.
691 SDValue Ops[] = { Op1, Op2 };
693 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 2);
694 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
698 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
699 /// were replaced with those specified. If this node is never memoized,
700 /// return null, otherwise return a pointer to the slot it would take. If a
701 /// node already exists with these operands, the slot will be non-null.
702 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
703 const SDValue *Ops,unsigned NumOps,
705 if (N->getValueType(0) == MVT::Flag)
706 return 0; // Never CSE anything that produces a flag.
708 switch (N->getOpcode()) {
710 case ISD::HANDLENODE:
712 case ISD::DBG_STOPPOINT:
715 return 0; // Never add these nodes.
718 // Check that remaining values produced are not flags.
719 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
720 if (N->getValueType(i) == MVT::Flag)
721 return 0; // Never CSE anything that produces a flag.
724 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, NumOps);
726 if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
727 ID.AddInteger(LD->getAddressingMode());
728 ID.AddInteger(LD->getExtensionType());
729 ID.AddInteger(LD->getMemoryVT().getRawBits());
730 ID.AddInteger(LD->getAlignment());
731 ID.AddInteger(LD->isVolatile());
732 } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
733 ID.AddInteger(ST->getAddressingMode());
734 ID.AddInteger(ST->isTruncatingStore());
735 ID.AddInteger(ST->getMemoryVT().getRawBits());
736 ID.AddInteger(ST->getAlignment());
737 ID.AddInteger(ST->isVolatile());
740 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
743 /// VerifyNode - Sanity check the given node. Aborts if it is invalid.
744 void SelectionDAG::VerifyNode(SDNode *N) {
745 switch (N->getOpcode()) {
748 case ISD::BUILD_VECTOR: {
749 assert(N->getNumValues() == 1 && "Too many results for BUILD_VECTOR!");
750 assert(N->getValueType(0).isVector() && "Wrong BUILD_VECTOR return type!");
751 assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
752 "Wrong number of BUILD_VECTOR operands!");
753 MVT EltVT = N->getValueType(0).getVectorElementType();
754 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I)
755 assert(I->getSDValue().getValueType() == EltVT &&
756 "Wrong BUILD_VECTOR operand type!");
762 /// getMVTAlignment - Compute the default alignment value for the
765 unsigned SelectionDAG::getMVTAlignment(MVT VT) const {
766 const Type *Ty = VT == MVT::iPTR ?
767 PointerType::get(Type::Int8Ty, 0) :
770 return TLI.getTargetData()->getABITypeAlignment(Ty);
773 SelectionDAG::~SelectionDAG() {
774 while (!AllNodes.empty()) {
775 SDNode *N = AllNodes.begin();
776 N->SetNextInBucket(0);
777 if (N->OperandsNeedDelete) {
778 delete [] N->OperandList;
782 AllNodes.pop_front();
786 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, MVT VT) {
787 if (Op.getValueType() == VT) return Op;
788 APInt Imm = APInt::getLowBitsSet(Op.getValueSizeInBits(),
790 return getNode(ISD::AND, Op.getValueType(), Op,
791 getConstant(Imm, Op.getValueType()));
794 SDValue SelectionDAG::getConstant(uint64_t Val, MVT VT, bool isT) {
795 MVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
796 return getConstant(APInt(EltVT.getSizeInBits(), Val), VT, isT);
799 SDValue SelectionDAG::getConstant(const APInt &Val, MVT VT, bool isT) {
800 assert(VT.isInteger() && "Cannot create FP integer constant!");
802 MVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
803 assert(Val.getBitWidth() == EltVT.getSizeInBits() &&
804 "APInt size does not match type size!");
806 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
808 AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0);
812 if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
814 return SDValue(N, 0);
816 N = getAllocator().Allocate<ConstantSDNode>();
817 new (N) ConstantSDNode(isT, Val, EltVT);
818 CSEMap.InsertNode(N, IP);
819 AllNodes.push_back(N);
822 SDValue Result(N, 0);
824 SmallVector<SDValue, 8> Ops;
825 Ops.assign(VT.getVectorNumElements(), Result);
826 Result = getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
831 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, bool isTarget) {
832 return getConstant(Val, TLI.getPointerTy(), isTarget);
836 SDValue SelectionDAG::getConstantFP(const APFloat& V, MVT VT, bool isTarget) {
837 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
840 VT.isVector() ? VT.getVectorElementType() : VT;
842 // Do the map lookup using the actual bit pattern for the floating point
843 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
844 // we don't have issues with SNANs.
845 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
847 AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0);
851 if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
853 return SDValue(N, 0);
855 N = getAllocator().Allocate<ConstantFPSDNode>();
856 new (N) ConstantFPSDNode(isTarget, V, EltVT);
857 CSEMap.InsertNode(N, IP);
858 AllNodes.push_back(N);
861 SDValue Result(N, 0);
863 SmallVector<SDValue, 8> Ops;
864 Ops.assign(VT.getVectorNumElements(), Result);
865 Result = getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
870 SDValue SelectionDAG::getConstantFP(double Val, MVT VT, bool isTarget) {
872 VT.isVector() ? VT.getVectorElementType() : VT;
874 return getConstantFP(APFloat((float)Val), VT, isTarget);
876 return getConstantFP(APFloat(Val), VT, isTarget);
879 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV,
884 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
886 // If GV is an alias then use the aliasee for determining thread-localness.
887 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
888 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal());
891 if (GVar && GVar->isThreadLocal())
892 Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
894 Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
897 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
899 ID.AddInteger(Offset);
901 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
902 return SDValue(E, 0);
903 SDNode *N = getAllocator().Allocate<GlobalAddressSDNode>();
904 new (N) GlobalAddressSDNode(isTargetGA, GV, VT, Offset);
905 CSEMap.InsertNode(N, IP);
906 AllNodes.push_back(N);
907 return SDValue(N, 0);
910 SDValue SelectionDAG::getFrameIndex(int FI, MVT VT, bool isTarget) {
911 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
913 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
916 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
917 return SDValue(E, 0);
918 SDNode *N = getAllocator().Allocate<FrameIndexSDNode>();
919 new (N) FrameIndexSDNode(FI, VT, isTarget);
920 CSEMap.InsertNode(N, IP);
921 AllNodes.push_back(N);
922 return SDValue(N, 0);
925 SDValue SelectionDAG::getJumpTable(int JTI, MVT VT, bool isTarget){
926 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
928 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
931 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
932 return SDValue(E, 0);
933 SDNode *N = getAllocator().Allocate<JumpTableSDNode>();
934 new (N) JumpTableSDNode(JTI, VT, isTarget);
935 CSEMap.InsertNode(N, IP);
936 AllNodes.push_back(N);
937 return SDValue(N, 0);
940 SDValue SelectionDAG::getConstantPool(Constant *C, MVT VT,
941 unsigned Alignment, int Offset,
943 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
945 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
946 ID.AddInteger(Alignment);
947 ID.AddInteger(Offset);
950 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
951 return SDValue(E, 0);
952 SDNode *N = getAllocator().Allocate<ConstantPoolSDNode>();
953 new (N) ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment);
954 CSEMap.InsertNode(N, IP);
955 AllNodes.push_back(N);
956 return SDValue(N, 0);
960 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, MVT VT,
961 unsigned Alignment, int Offset,
963 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
965 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
966 ID.AddInteger(Alignment);
967 ID.AddInteger(Offset);
968 C->AddSelectionDAGCSEId(ID);
970 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
971 return SDValue(E, 0);
972 SDNode *N = getAllocator().Allocate<ConstantPoolSDNode>();
973 new (N) ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment);
974 CSEMap.InsertNode(N, IP);
975 AllNodes.push_back(N);
976 return SDValue(N, 0);
980 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
982 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), 0, 0);
985 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
986 return SDValue(E, 0);
987 SDNode *N = getAllocator().Allocate<BasicBlockSDNode>();
988 new (N) BasicBlockSDNode(MBB);
989 CSEMap.InsertNode(N, IP);
990 AllNodes.push_back(N);
991 return SDValue(N, 0);
994 SDValue SelectionDAG::getArgFlags(ISD::ArgFlagsTy Flags) {
996 AddNodeIDNode(ID, ISD::ARG_FLAGS, getVTList(MVT::Other), 0, 0);
997 ID.AddInteger(Flags.getRawBits());
999 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1000 return SDValue(E, 0);
1001 SDNode *N = getAllocator().Allocate<ARG_FLAGSSDNode>();
1002 new (N) ARG_FLAGSSDNode(Flags);
1003 CSEMap.InsertNode(N, IP);
1004 AllNodes.push_back(N);
1005 return SDValue(N, 0);
1008 SDValue SelectionDAG::getValueType(MVT VT) {
1009 if (VT.isSimple() && (unsigned)VT.getSimpleVT() >= ValueTypeNodes.size())
1010 ValueTypeNodes.resize(VT.getSimpleVT()+1);
1012 SDNode *&N = VT.isExtended() ?
1013 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT()];
1015 if (N) return SDValue(N, 0);
1016 N = getAllocator().Allocate<VTSDNode>();
1017 new (N) VTSDNode(VT);
1018 AllNodes.push_back(N);
1019 return SDValue(N, 0);
1022 SDValue SelectionDAG::getExternalSymbol(const char *Sym, MVT VT) {
1023 SDNode *&N = ExternalSymbols[Sym];
1024 if (N) return SDValue(N, 0);
1025 N = getAllocator().Allocate<ExternalSymbolSDNode>();
1026 new (N) ExternalSymbolSDNode(false, Sym, VT);
1027 AllNodes.push_back(N);
1028 return SDValue(N, 0);
1031 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, MVT VT) {
1032 SDNode *&N = TargetExternalSymbols[Sym];
1033 if (N) return SDValue(N, 0);
1034 N = getAllocator().Allocate<ExternalSymbolSDNode>();
1035 new (N) ExternalSymbolSDNode(true, Sym, VT);
1036 AllNodes.push_back(N);
1037 return SDValue(N, 0);
1040 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
1041 if ((unsigned)Cond >= CondCodeNodes.size())
1042 CondCodeNodes.resize(Cond+1);
1044 if (CondCodeNodes[Cond] == 0) {
1045 CondCodeSDNode *N = getAllocator().Allocate<CondCodeSDNode>();
1046 new (N) CondCodeSDNode(Cond);
1047 CondCodeNodes[Cond] = N;
1048 AllNodes.push_back(N);
1050 return SDValue(CondCodeNodes[Cond], 0);
1053 SDValue SelectionDAG::getRegister(unsigned RegNo, MVT VT) {
1054 FoldingSetNodeID ID;
1055 AddNodeIDNode(ID, ISD::Register, getVTList(VT), 0, 0);
1056 ID.AddInteger(RegNo);
1058 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1059 return SDValue(E, 0);
1060 SDNode *N = getAllocator().Allocate<RegisterSDNode>();
1061 new (N) RegisterSDNode(RegNo, VT);
1062 CSEMap.InsertNode(N, IP);
1063 AllNodes.push_back(N);
1064 return SDValue(N, 0);
1067 SDValue SelectionDAG::getDbgStopPoint(SDValue Root,
1068 unsigned Line, unsigned Col,
1069 const CompileUnitDesc *CU) {
1070 SDNode *N = getAllocator().Allocate<DbgStopPointSDNode>();
1071 new (N) DbgStopPointSDNode(Root, Line, Col, CU);
1072 AllNodes.push_back(N);
1073 return SDValue(N, 0);
1076 SDValue SelectionDAG::getLabel(unsigned Opcode,
1079 FoldingSetNodeID ID;
1080 SDValue Ops[] = { Root };
1081 AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), &Ops[0], 1);
1082 ID.AddInteger(LabelID);
1084 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1085 return SDValue(E, 0);
1086 SDNode *N = getAllocator().Allocate<LabelSDNode>();
1087 new (N) LabelSDNode(Opcode, Root, LabelID);
1088 CSEMap.InsertNode(N, IP);
1089 AllNodes.push_back(N);
1090 return SDValue(N, 0);
1093 SDValue SelectionDAG::getSrcValue(const Value *V) {
1094 assert((!V || isa<PointerType>(V->getType())) &&
1095 "SrcValue is not a pointer?");
1097 FoldingSetNodeID ID;
1098 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), 0, 0);
1102 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1103 return SDValue(E, 0);
1105 SDNode *N = getAllocator().Allocate<SrcValueSDNode>();
1106 new (N) SrcValueSDNode(V);
1107 CSEMap.InsertNode(N, IP);
1108 AllNodes.push_back(N);
1109 return SDValue(N, 0);
1112 SDValue SelectionDAG::getMemOperand(const MachineMemOperand &MO) {
1113 const Value *v = MO.getValue();
1114 assert((!v || isa<PointerType>(v->getType())) &&
1115 "SrcValue is not a pointer?");
1117 FoldingSetNodeID ID;
1118 AddNodeIDNode(ID, ISD::MEMOPERAND, getVTList(MVT::Other), 0, 0);
1120 ID.AddInteger(MO.getFlags());
1121 ID.AddInteger(MO.getOffset());
1122 ID.AddInteger(MO.getSize());
1123 ID.AddInteger(MO.getAlignment());
1126 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1127 return SDValue(E, 0);
1129 SDNode *N = getAllocator().Allocate<MemOperandSDNode>();
1130 new (N) MemOperandSDNode(MO);
1131 CSEMap.InsertNode(N, IP);
1132 AllNodes.push_back(N);
1133 return SDValue(N, 0);
1136 /// CreateStackTemporary - Create a stack temporary, suitable for holding the
1137 /// specified value type.
1138 SDValue SelectionDAG::CreateStackTemporary(MVT VT, unsigned minAlign) {
1139 MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo();
1140 unsigned ByteSize = VT.getSizeInBits()/8;
1141 const Type *Ty = VT.getTypeForMVT();
1142 unsigned StackAlign =
1143 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty), minAlign);
1145 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign);
1146 return getFrameIndex(FrameIdx, TLI.getPointerTy());
1149 SDValue SelectionDAG::FoldSetCC(MVT VT, SDValue N1,
1150 SDValue N2, ISD::CondCode Cond) {
1151 // These setcc operations always fold.
1155 case ISD::SETFALSE2: return getConstant(0, VT);
1157 case ISD::SETTRUE2: return getConstant(1, VT);
1169 assert(!N1.getValueType().isInteger() && "Illegal setcc for integer!");
1173 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val)) {
1174 const APInt &C2 = N2C->getAPIntValue();
1175 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val)) {
1176 const APInt &C1 = N1C->getAPIntValue();
1179 default: assert(0 && "Unknown integer setcc!");
1180 case ISD::SETEQ: return getConstant(C1 == C2, VT);
1181 case ISD::SETNE: return getConstant(C1 != C2, VT);
1182 case ISD::SETULT: return getConstant(C1.ult(C2), VT);
1183 case ISD::SETUGT: return getConstant(C1.ugt(C2), VT);
1184 case ISD::SETULE: return getConstant(C1.ule(C2), VT);
1185 case ISD::SETUGE: return getConstant(C1.uge(C2), VT);
1186 case ISD::SETLT: return getConstant(C1.slt(C2), VT);
1187 case ISD::SETGT: return getConstant(C1.sgt(C2), VT);
1188 case ISD::SETLE: return getConstant(C1.sle(C2), VT);
1189 case ISD::SETGE: return getConstant(C1.sge(C2), VT);
1193 if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1.Val)) {
1194 if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2.Val)) {
1195 // No compile time operations on this type yet.
1196 if (N1C->getValueType(0) == MVT::ppcf128)
1199 APFloat::cmpResult R = N1C->getValueAPF().compare(N2C->getValueAPF());
1202 case ISD::SETEQ: if (R==APFloat::cmpUnordered)
1203 return getNode(ISD::UNDEF, VT);
1205 case ISD::SETOEQ: return getConstant(R==APFloat::cmpEqual, VT);
1206 case ISD::SETNE: if (R==APFloat::cmpUnordered)
1207 return getNode(ISD::UNDEF, VT);
1209 case ISD::SETONE: return getConstant(R==APFloat::cmpGreaterThan ||
1210 R==APFloat::cmpLessThan, VT);
1211 case ISD::SETLT: if (R==APFloat::cmpUnordered)
1212 return getNode(ISD::UNDEF, VT);
1214 case ISD::SETOLT: return getConstant(R==APFloat::cmpLessThan, VT);
1215 case ISD::SETGT: if (R==APFloat::cmpUnordered)
1216 return getNode(ISD::UNDEF, VT);
1218 case ISD::SETOGT: return getConstant(R==APFloat::cmpGreaterThan, VT);
1219 case ISD::SETLE: if (R==APFloat::cmpUnordered)
1220 return getNode(ISD::UNDEF, VT);
1222 case ISD::SETOLE: return getConstant(R==APFloat::cmpLessThan ||
1223 R==APFloat::cmpEqual, VT);
1224 case ISD::SETGE: if (R==APFloat::cmpUnordered)
1225 return getNode(ISD::UNDEF, VT);
1227 case ISD::SETOGE: return getConstant(R==APFloat::cmpGreaterThan ||
1228 R==APFloat::cmpEqual, VT);
1229 case ISD::SETO: return getConstant(R!=APFloat::cmpUnordered, VT);
1230 case ISD::SETUO: return getConstant(R==APFloat::cmpUnordered, VT);
1231 case ISD::SETUEQ: return getConstant(R==APFloat::cmpUnordered ||
1232 R==APFloat::cmpEqual, VT);
1233 case ISD::SETUNE: return getConstant(R!=APFloat::cmpEqual, VT);
1234 case ISD::SETULT: return getConstant(R==APFloat::cmpUnordered ||
1235 R==APFloat::cmpLessThan, VT);
1236 case ISD::SETUGT: return getConstant(R==APFloat::cmpGreaterThan ||
1237 R==APFloat::cmpUnordered, VT);
1238 case ISD::SETULE: return getConstant(R!=APFloat::cmpGreaterThan, VT);
1239 case ISD::SETUGE: return getConstant(R!=APFloat::cmpLessThan, VT);
1242 // Ensure that the constant occurs on the RHS.
1243 return getSetCC(VT, N2, N1, ISD::getSetCCSwappedOperands(Cond));
1247 // Could not fold it.
1251 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We
1252 /// use this predicate to simplify operations downstream.
1253 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
1254 unsigned BitWidth = Op.getValueSizeInBits();
1255 return MaskedValueIsZero(Op, APInt::getSignBit(BitWidth), Depth);
1258 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1259 /// this predicate to simplify operations downstream. Mask is known to be zero
1260 /// for bits that V cannot have.
1261 bool SelectionDAG::MaskedValueIsZero(SDValue Op, const APInt &Mask,
1262 unsigned Depth) const {
1263 APInt KnownZero, KnownOne;
1264 ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
1265 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1266 return (KnownZero & Mask) == Mask;
1269 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
1270 /// known to be either zero or one and return them in the KnownZero/KnownOne
1271 /// bitsets. This code only analyzes bits in Mask, in order to short-circuit
1273 void SelectionDAG::ComputeMaskedBits(SDValue Op, const APInt &Mask,
1274 APInt &KnownZero, APInt &KnownOne,
1275 unsigned Depth) const {
1276 unsigned BitWidth = Mask.getBitWidth();
1277 assert(BitWidth == Op.getValueType().getSizeInBits() &&
1278 "Mask size mismatches value type size!");
1280 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
1281 if (Depth == 6 || Mask == 0)
1282 return; // Limit search depth.
1284 APInt KnownZero2, KnownOne2;
1286 switch (Op.getOpcode()) {
1288 // We know all of the bits for a constant!
1289 KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue() & Mask;
1290 KnownZero = ~KnownOne & Mask;
1293 // If either the LHS or the RHS are Zero, the result is zero.
1294 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1295 ComputeMaskedBits(Op.getOperand(0), Mask & ~KnownZero,
1296 KnownZero2, KnownOne2, Depth+1);
1297 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1298 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1300 // Output known-1 bits are only known if set in both the LHS & RHS.
1301 KnownOne &= KnownOne2;
1302 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1303 KnownZero |= KnownZero2;
1306 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1307 ComputeMaskedBits(Op.getOperand(0), Mask & ~KnownOne,
1308 KnownZero2, KnownOne2, Depth+1);
1309 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1310 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1312 // Output known-0 bits are only known if clear in both the LHS & RHS.
1313 KnownZero &= KnownZero2;
1314 // Output known-1 are known to be set if set in either the LHS | RHS.
1315 KnownOne |= KnownOne2;
1318 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1319 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
1320 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1321 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1323 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1324 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
1325 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1326 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
1327 KnownZero = KnownZeroOut;
1331 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
1332 ComputeMaskedBits(Op.getOperand(1), Mask2, KnownZero, KnownOne, Depth+1);
1333 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
1334 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1335 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1337 // If low bits are zero in either operand, output low known-0 bits.
1338 // Also compute a conserative estimate for high known-0 bits.
1339 // More trickiness is possible, but this is sufficient for the
1340 // interesting case of alignment computation.
1342 unsigned TrailZ = KnownZero.countTrailingOnes() +
1343 KnownZero2.countTrailingOnes();
1344 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
1345 KnownZero2.countLeadingOnes(),
1346 BitWidth) - BitWidth;
1348 TrailZ = std::min(TrailZ, BitWidth);
1349 LeadZ = std::min(LeadZ, BitWidth);
1350 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
1351 APInt::getHighBitsSet(BitWidth, LeadZ);
1356 // For the purposes of computing leading zeros we can conservatively
1357 // treat a udiv as a logical right shift by the power of 2 known to
1358 // be less than the denominator.
1359 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1360 ComputeMaskedBits(Op.getOperand(0),
1361 AllOnes, KnownZero2, KnownOne2, Depth+1);
1362 unsigned LeadZ = KnownZero2.countLeadingOnes();
1366 ComputeMaskedBits(Op.getOperand(1),
1367 AllOnes, KnownZero2, KnownOne2, Depth+1);
1368 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
1369 if (RHSUnknownLeadingOnes != BitWidth)
1370 LeadZ = std::min(BitWidth,
1371 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
1373 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
1377 ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
1378 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
1379 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1380 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1382 // Only known if known in both the LHS and RHS.
1383 KnownOne &= KnownOne2;
1384 KnownZero &= KnownZero2;
1386 case ISD::SELECT_CC:
1387 ComputeMaskedBits(Op.getOperand(3), Mask, KnownZero, KnownOne, Depth+1);
1388 ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero2, KnownOne2, Depth+1);
1389 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1390 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1392 // Only known if known in both the LHS and RHS.
1393 KnownOne &= KnownOne2;
1394 KnownZero &= KnownZero2;
1397 // If we know the result of a setcc has the top bits zero, use this info.
1398 if (TLI.getSetCCResultContents() == TargetLowering::ZeroOrOneSetCCResult &&
1400 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
1403 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
1404 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1405 unsigned ShAmt = SA->getValue();
1407 // If the shift count is an invalid immediate, don't do anything.
1408 if (ShAmt >= BitWidth)
1411 ComputeMaskedBits(Op.getOperand(0), Mask.lshr(ShAmt),
1412 KnownZero, KnownOne, Depth+1);
1413 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1414 KnownZero <<= ShAmt;
1416 // low bits known zero.
1417 KnownZero |= APInt::getLowBitsSet(BitWidth, ShAmt);
1421 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
1422 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1423 unsigned ShAmt = SA->getValue();
1425 // If the shift count is an invalid immediate, don't do anything.
1426 if (ShAmt >= BitWidth)
1429 ComputeMaskedBits(Op.getOperand(0), (Mask << ShAmt),
1430 KnownZero, KnownOne, Depth+1);
1431 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1432 KnownZero = KnownZero.lshr(ShAmt);
1433 KnownOne = KnownOne.lshr(ShAmt);
1435 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt) & Mask;
1436 KnownZero |= HighBits; // High bits known zero.
1440 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1441 unsigned ShAmt = SA->getValue();
1443 // If the shift count is an invalid immediate, don't do anything.
1444 if (ShAmt >= BitWidth)
1447 APInt InDemandedMask = (Mask << ShAmt);
1448 // If any of the demanded bits are produced by the sign extension, we also
1449 // demand the input sign bit.
1450 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt) & Mask;
1451 if (HighBits.getBoolValue())
1452 InDemandedMask |= APInt::getSignBit(BitWidth);
1454 ComputeMaskedBits(Op.getOperand(0), InDemandedMask, KnownZero, KnownOne,
1456 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1457 KnownZero = KnownZero.lshr(ShAmt);
1458 KnownOne = KnownOne.lshr(ShAmt);
1460 // Handle the sign bits.
1461 APInt SignBit = APInt::getSignBit(BitWidth);
1462 SignBit = SignBit.lshr(ShAmt); // Adjust to where it is now in the mask.
1464 if (KnownZero.intersects(SignBit)) {
1465 KnownZero |= HighBits; // New bits are known zero.
1466 } else if (KnownOne.intersects(SignBit)) {
1467 KnownOne |= HighBits; // New bits are known one.
1471 case ISD::SIGN_EXTEND_INREG: {
1472 MVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1473 unsigned EBits = EVT.getSizeInBits();
1475 // Sign extension. Compute the demanded bits in the result that are not
1476 // present in the input.
1477 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - EBits) & Mask;
1479 APInt InSignBit = APInt::getSignBit(EBits);
1480 APInt InputDemandedBits = Mask & APInt::getLowBitsSet(BitWidth, EBits);
1482 // If the sign extended bits are demanded, we know that the sign
1484 InSignBit.zext(BitWidth);
1485 if (NewBits.getBoolValue())
1486 InputDemandedBits |= InSignBit;
1488 ComputeMaskedBits(Op.getOperand(0), InputDemandedBits,
1489 KnownZero, KnownOne, Depth+1);
1490 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1492 // If the sign bit of the input is known set or clear, then we know the
1493 // top bits of the result.
1494 if (KnownZero.intersects(InSignBit)) { // Input sign bit known clear
1495 KnownZero |= NewBits;
1496 KnownOne &= ~NewBits;
1497 } else if (KnownOne.intersects(InSignBit)) { // Input sign bit known set
1498 KnownOne |= NewBits;
1499 KnownZero &= ~NewBits;
1500 } else { // Input sign bit unknown
1501 KnownZero &= ~NewBits;
1502 KnownOne &= ~NewBits;
1509 unsigned LowBits = Log2_32(BitWidth)+1;
1510 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1515 if (ISD::isZEXTLoad(Op.Val)) {
1516 LoadSDNode *LD = cast<LoadSDNode>(Op);
1517 MVT VT = LD->getMemoryVT();
1518 unsigned MemBits = VT.getSizeInBits();
1519 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits) & Mask;
1523 case ISD::ZERO_EXTEND: {
1524 MVT InVT = Op.getOperand(0).getValueType();
1525 unsigned InBits = InVT.getSizeInBits();
1526 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits) & Mask;
1527 APInt InMask = Mask;
1528 InMask.trunc(InBits);
1529 KnownZero.trunc(InBits);
1530 KnownOne.trunc(InBits);
1531 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1532 KnownZero.zext(BitWidth);
1533 KnownOne.zext(BitWidth);
1534 KnownZero |= NewBits;
1537 case ISD::SIGN_EXTEND: {
1538 MVT InVT = Op.getOperand(0).getValueType();
1539 unsigned InBits = InVT.getSizeInBits();
1540 APInt InSignBit = APInt::getSignBit(InBits);
1541 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits) & Mask;
1542 APInt InMask = Mask;
1543 InMask.trunc(InBits);
1545 // If any of the sign extended bits are demanded, we know that the sign
1546 // bit is demanded. Temporarily set this bit in the mask for our callee.
1547 if (NewBits.getBoolValue())
1548 InMask |= InSignBit;
1550 KnownZero.trunc(InBits);
1551 KnownOne.trunc(InBits);
1552 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1554 // Note if the sign bit is known to be zero or one.
1555 bool SignBitKnownZero = KnownZero.isNegative();
1556 bool SignBitKnownOne = KnownOne.isNegative();
1557 assert(!(SignBitKnownZero && SignBitKnownOne) &&
1558 "Sign bit can't be known to be both zero and one!");
1560 // If the sign bit wasn't actually demanded by our caller, we don't
1561 // want it set in the KnownZero and KnownOne result values. Reset the
1562 // mask and reapply it to the result values.
1564 InMask.trunc(InBits);
1565 KnownZero &= InMask;
1568 KnownZero.zext(BitWidth);
1569 KnownOne.zext(BitWidth);
1571 // If the sign bit is known zero or one, the top bits match.
1572 if (SignBitKnownZero)
1573 KnownZero |= NewBits;
1574 else if (SignBitKnownOne)
1575 KnownOne |= NewBits;
1578 case ISD::ANY_EXTEND: {
1579 MVT InVT = Op.getOperand(0).getValueType();
1580 unsigned InBits = InVT.getSizeInBits();
1581 APInt InMask = Mask;
1582 InMask.trunc(InBits);
1583 KnownZero.trunc(InBits);
1584 KnownOne.trunc(InBits);
1585 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1586 KnownZero.zext(BitWidth);
1587 KnownOne.zext(BitWidth);
1590 case ISD::TRUNCATE: {
1591 MVT InVT = Op.getOperand(0).getValueType();
1592 unsigned InBits = InVT.getSizeInBits();
1593 APInt InMask = Mask;
1594 InMask.zext(InBits);
1595 KnownZero.zext(InBits);
1596 KnownOne.zext(InBits);
1597 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1598 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1599 KnownZero.trunc(BitWidth);
1600 KnownOne.trunc(BitWidth);
1603 case ISD::AssertZext: {
1604 MVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1605 APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
1606 ComputeMaskedBits(Op.getOperand(0), Mask & InMask, KnownZero,
1608 KnownZero |= (~InMask) & Mask;
1612 // All bits are zero except the low bit.
1613 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - 1);
1617 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0))) {
1618 // We know that the top bits of C-X are clear if X contains less bits
1619 // than C (i.e. no wrap-around can happen). For example, 20-X is
1620 // positive if we can prove that X is >= 0 and < 16.
1621 if (CLHS->getAPIntValue().isNonNegative()) {
1622 unsigned NLZ = (CLHS->getAPIntValue()+1).countLeadingZeros();
1623 // NLZ can't be BitWidth with no sign bit
1624 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
1625 ComputeMaskedBits(Op.getOperand(1), MaskV, KnownZero2, KnownOne2,
1628 // If all of the MaskV bits are known to be zero, then we know the
1629 // output top bits are zero, because we now know that the output is
1631 if ((KnownZero2 & MaskV) == MaskV) {
1632 unsigned NLZ2 = CLHS->getAPIntValue().countLeadingZeros();
1633 // Top bits known zero.
1634 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
1641 // Output known-0 bits are known if clear or set in both the low clear bits
1642 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
1643 // low 3 bits clear.
1644 APInt Mask2 = APInt::getLowBitsSet(BitWidth, Mask.countTrailingOnes());
1645 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
1646 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1647 unsigned KnownZeroOut = KnownZero2.countTrailingOnes();
1649 ComputeMaskedBits(Op.getOperand(1), Mask2, KnownZero2, KnownOne2, Depth+1);
1650 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1651 KnownZeroOut = std::min(KnownZeroOut,
1652 KnownZero2.countTrailingOnes());
1654 KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroOut);
1658 if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1659 const APInt &RA = Rem->getAPIntValue();
1660 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
1661 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
1662 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1663 ComputeMaskedBits(Op.getOperand(0), Mask2,KnownZero2,KnownOne2,Depth+1);
1665 // The sign of a remainder is equal to the sign of the first
1666 // operand (zero being positive).
1667 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
1668 KnownZero2 |= ~LowBits;
1669 else if (KnownOne2[BitWidth-1])
1670 KnownOne2 |= ~LowBits;
1672 KnownZero |= KnownZero2 & Mask;
1673 KnownOne |= KnownOne2 & Mask;
1675 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1680 if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1681 const APInt &RA = Rem->getAPIntValue();
1682 if (RA.isPowerOf2()) {
1683 APInt LowBits = (RA - 1);
1684 APInt Mask2 = LowBits & Mask;
1685 KnownZero |= ~LowBits & Mask;
1686 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero, KnownOne,Depth+1);
1687 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1692 // Since the result is less than or equal to either operand, any leading
1693 // zero bits in either operand must also exist in the result.
1694 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1695 ComputeMaskedBits(Op.getOperand(0), AllOnes, KnownZero, KnownOne,
1697 ComputeMaskedBits(Op.getOperand(1), AllOnes, KnownZero2, KnownOne2,
1700 uint32_t Leaders = std::max(KnownZero.countLeadingOnes(),
1701 KnownZero2.countLeadingOnes());
1703 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
1707 // Allow the target to implement this method for its nodes.
1708 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) {
1709 case ISD::INTRINSIC_WO_CHAIN:
1710 case ISD::INTRINSIC_W_CHAIN:
1711 case ISD::INTRINSIC_VOID:
1712 TLI.computeMaskedBitsForTargetNode(Op, Mask, KnownZero, KnownOne, *this);
1718 /// ComputeNumSignBits - Return the number of times the sign bit of the
1719 /// register is replicated into the other bits. We know that at least 1 bit
1720 /// is always equal to the sign bit (itself), but other cases can give us
1721 /// information. For example, immediately after an "SRA X, 2", we know that
1722 /// the top 3 bits are all equal to each other, so we return 3.
1723 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const{
1724 MVT VT = Op.getValueType();
1725 assert(VT.isInteger() && "Invalid VT!");
1726 unsigned VTBits = VT.getSizeInBits();
1728 unsigned FirstAnswer = 1;
1731 return 1; // Limit search depth.
1733 switch (Op.getOpcode()) {
1735 case ISD::AssertSext:
1736 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
1737 return VTBits-Tmp+1;
1738 case ISD::AssertZext:
1739 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
1742 case ISD::Constant: {
1743 const APInt &Val = cast<ConstantSDNode>(Op)->getAPIntValue();
1744 // If negative, return # leading ones.
1745 if (Val.isNegative())
1746 return Val.countLeadingOnes();
1748 // Return # leading zeros.
1749 return Val.countLeadingZeros();
1752 case ISD::SIGN_EXTEND:
1753 Tmp = VTBits-Op.getOperand(0).getValueType().getSizeInBits();
1754 return ComputeNumSignBits(Op.getOperand(0), Depth+1) + Tmp;
1756 case ISD::SIGN_EXTEND_INREG:
1757 // Max of the input and what this extends.
1758 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
1761 Tmp2 = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1762 return std::max(Tmp, Tmp2);
1765 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1766 // SRA X, C -> adds C sign bits.
1767 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1768 Tmp += C->getValue();
1769 if (Tmp > VTBits) Tmp = VTBits;
1773 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1774 // shl destroys sign bits.
1775 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1776 if (C->getValue() >= VTBits || // Bad shift.
1777 C->getValue() >= Tmp) break; // Shifted all sign bits out.
1778 return Tmp - C->getValue();
1783 case ISD::XOR: // NOT is handled here.
1784 // Logical binary ops preserve the number of sign bits at the worst.
1785 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1787 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1788 FirstAnswer = std::min(Tmp, Tmp2);
1789 // We computed what we know about the sign bits as our first
1790 // answer. Now proceed to the generic code that uses
1791 // ComputeMaskedBits, and pick whichever answer is better.
1796 Tmp = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1797 if (Tmp == 1) return 1; // Early out.
1798 Tmp2 = ComputeNumSignBits(Op.getOperand(2), Depth+1);
1799 return std::min(Tmp, Tmp2);
1802 // If setcc returns 0/-1, all bits are sign bits.
1803 if (TLI.getSetCCResultContents() ==
1804 TargetLowering::ZeroOrNegativeOneSetCCResult)
1809 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1810 unsigned RotAmt = C->getValue() & (VTBits-1);
1812 // Handle rotate right by N like a rotate left by 32-N.
1813 if (Op.getOpcode() == ISD::ROTR)
1814 RotAmt = (VTBits-RotAmt) & (VTBits-1);
1816 // If we aren't rotating out all of the known-in sign bits, return the
1817 // number that are left. This handles rotl(sext(x), 1) for example.
1818 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1819 if (Tmp > RotAmt+1) return Tmp-RotAmt;
1823 // Add can have at most one carry bit. Thus we know that the output
1824 // is, at worst, one more bit than the inputs.
1825 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1826 if (Tmp == 1) return 1; // Early out.
1828 // Special case decrementing a value (ADD X, -1):
1829 if (ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
1830 if (CRHS->isAllOnesValue()) {
1831 APInt KnownZero, KnownOne;
1832 APInt Mask = APInt::getAllOnesValue(VTBits);
1833 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
1835 // If the input is known to be 0 or 1, the output is 0/-1, which is all
1837 if ((KnownZero | APInt(VTBits, 1)) == Mask)
1840 // If we are subtracting one from a positive number, there is no carry
1841 // out of the result.
1842 if (KnownZero.isNegative())
1846 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1847 if (Tmp2 == 1) return 1;
1848 return std::min(Tmp, Tmp2)-1;
1852 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1853 if (Tmp2 == 1) return 1;
1856 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
1857 if (CLHS->isNullValue()) {
1858 APInt KnownZero, KnownOne;
1859 APInt Mask = APInt::getAllOnesValue(VTBits);
1860 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1861 // If the input is known to be 0 or 1, the output is 0/-1, which is all
1863 if ((KnownZero | APInt(VTBits, 1)) == Mask)
1866 // If the input is known to be positive (the sign bit is known clear),
1867 // the output of the NEG has the same number of sign bits as the input.
1868 if (KnownZero.isNegative())
1871 // Otherwise, we treat this like a SUB.
1874 // Sub can have at most one carry bit. Thus we know that the output
1875 // is, at worst, one more bit than the inputs.
1876 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1877 if (Tmp == 1) return 1; // Early out.
1878 return std::min(Tmp, Tmp2)-1;
1881 // FIXME: it's tricky to do anything useful for this, but it is an important
1882 // case for targets like X86.
1886 // Handle LOADX separately here. EXTLOAD case will fallthrough.
1887 if (Op.getOpcode() == ISD::LOAD) {
1888 LoadSDNode *LD = cast<LoadSDNode>(Op);
1889 unsigned ExtType = LD->getExtensionType();
1892 case ISD::SEXTLOAD: // '17' bits known
1893 Tmp = LD->getMemoryVT().getSizeInBits();
1894 return VTBits-Tmp+1;
1895 case ISD::ZEXTLOAD: // '16' bits known
1896 Tmp = LD->getMemoryVT().getSizeInBits();
1901 // Allow the target to implement this method for its nodes.
1902 if (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
1903 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1904 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
1905 Op.getOpcode() == ISD::INTRINSIC_VOID) {
1906 unsigned NumBits = TLI.ComputeNumSignBitsForTargetNode(Op, Depth);
1907 if (NumBits > 1) FirstAnswer = std::max(FirstAnswer, NumBits);
1910 // Finally, if we can prove that the top bits of the result are 0's or 1's,
1911 // use this information.
1912 APInt KnownZero, KnownOne;
1913 APInt Mask = APInt::getAllOnesValue(VTBits);
1914 ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
1916 if (KnownZero.isNegative()) { // sign bit is 0
1918 } else if (KnownOne.isNegative()) { // sign bit is 1;
1925 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
1926 // the number of identical bits in the top of the input value.
1928 Mask <<= Mask.getBitWidth()-VTBits;
1929 // Return # leading zeros. We use 'min' here in case Val was zero before
1930 // shifting. We don't want to return '64' as for an i32 "0".
1931 return std::max(FirstAnswer, std::min(VTBits, Mask.countLeadingZeros()));
1935 bool SelectionDAG::isVerifiedDebugInfoDesc(SDValue Op) const {
1936 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
1937 if (!GA) return false;
1938 GlobalVariable *GV = dyn_cast<GlobalVariable>(GA->getGlobal());
1939 if (!GV) return false;
1940 MachineModuleInfo *MMI = getMachineModuleInfo();
1941 return MMI && MMI->hasDebugInfo() && MMI->isVerified(GV);
1945 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
1946 /// element of the result of the vector shuffle.
1947 SDValue SelectionDAG::getShuffleScalarElt(const SDNode *N, unsigned i) {
1948 MVT VT = N->getValueType(0);
1949 SDValue PermMask = N->getOperand(2);
1950 SDValue Idx = PermMask.getOperand(i);
1951 if (Idx.getOpcode() == ISD::UNDEF)
1952 return getNode(ISD::UNDEF, VT.getVectorElementType());
1953 unsigned Index = cast<ConstantSDNode>(Idx)->getValue();
1954 unsigned NumElems = PermMask.getNumOperands();
1955 SDValue V = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
1958 if (V.getOpcode() == ISD::BIT_CONVERT) {
1959 V = V.getOperand(0);
1960 if (V.getValueType().getVectorNumElements() != NumElems)
1963 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
1964 return (Index == 0) ? V.getOperand(0)
1965 : getNode(ISD::UNDEF, VT.getVectorElementType());
1966 if (V.getOpcode() == ISD::BUILD_VECTOR)
1967 return V.getOperand(Index);
1968 if (V.getOpcode() == ISD::VECTOR_SHUFFLE)
1969 return getShuffleScalarElt(V.Val, Index);
1974 /// getNode - Gets or creates the specified node.
1976 SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT) {
1977 FoldingSetNodeID ID;
1978 AddNodeIDNode(ID, Opcode, getVTList(VT), 0, 0);
1980 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1981 return SDValue(E, 0);
1982 SDNode *N = getAllocator().Allocate<SDNode>();
1983 new (N) SDNode(Opcode, SDNode::getSDVTList(VT));
1984 CSEMap.InsertNode(N, IP);
1986 AllNodes.push_back(N);
1990 return SDValue(N, 0);
1993 SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT, SDValue Operand) {
1994 // Constant fold unary operations with an integer constant operand.
1995 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand.Val)) {
1996 const APInt &Val = C->getAPIntValue();
1997 unsigned BitWidth = VT.getSizeInBits();
2000 case ISD::SIGN_EXTEND:
2001 return getConstant(APInt(Val).sextOrTrunc(BitWidth), VT);
2002 case ISD::ANY_EXTEND:
2003 case ISD::ZERO_EXTEND:
2005 return getConstant(APInt(Val).zextOrTrunc(BitWidth), VT);
2006 case ISD::UINT_TO_FP:
2007 case ISD::SINT_TO_FP: {
2008 const uint64_t zero[] = {0, 0};
2009 // No compile time operations on this type.
2010 if (VT==MVT::ppcf128)
2012 APFloat apf = APFloat(APInt(BitWidth, 2, zero));
2013 (void)apf.convertFromAPInt(Val,
2014 Opcode==ISD::SINT_TO_FP,
2015 APFloat::rmNearestTiesToEven);
2016 return getConstantFP(apf, VT);
2018 case ISD::BIT_CONVERT:
2019 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
2020 return getConstantFP(Val.bitsToFloat(), VT);
2021 else if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
2022 return getConstantFP(Val.bitsToDouble(), VT);
2025 return getConstant(Val.byteSwap(), VT);
2027 return getConstant(Val.countPopulation(), VT);
2029 return getConstant(Val.countLeadingZeros(), VT);
2031 return getConstant(Val.countTrailingZeros(), VT);
2035 // Constant fold unary operations with a floating point constant operand.
2036 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand.Val)) {
2037 APFloat V = C->getValueAPF(); // make copy
2038 if (VT != MVT::ppcf128 && Operand.getValueType() != MVT::ppcf128) {
2042 return getConstantFP(V, VT);
2045 return getConstantFP(V, VT);
2047 case ISD::FP_EXTEND:
2048 // This can return overflow, underflow, or inexact; we don't care.
2049 // FIXME need to be more flexible about rounding mode.
2050 (void)V.convert(*MVTToAPFloatSemantics(VT),
2051 APFloat::rmNearestTiesToEven);
2052 return getConstantFP(V, VT);
2053 case ISD::FP_TO_SINT:
2054 case ISD::FP_TO_UINT: {
2056 assert(integerPartWidth >= 64);
2057 // FIXME need to be more flexible about rounding mode.
2058 APFloat::opStatus s = V.convertToInteger(&x, 64U,
2059 Opcode==ISD::FP_TO_SINT,
2060 APFloat::rmTowardZero);
2061 if (s==APFloat::opInvalidOp) // inexact is OK, in fact usual
2063 return getConstant(x, VT);
2065 case ISD::BIT_CONVERT:
2066 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
2067 return getConstant((uint32_t)V.convertToAPInt().getZExtValue(), VT);
2068 else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
2069 return getConstant(V.convertToAPInt().getZExtValue(), VT);
2075 unsigned OpOpcode = Operand.Val->getOpcode();
2077 case ISD::TokenFactor:
2078 return Operand; // Factor of one node? No need.
2079 case ISD::FP_ROUND: assert(0 && "Invalid method to make FP_ROUND node");
2080 case ISD::FP_EXTEND:
2081 assert(VT.isFloatingPoint() &&
2082 Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
2083 if (Operand.getValueType() == VT) return Operand; // noop conversion.
2084 if (Operand.getOpcode() == ISD::UNDEF)
2085 return getNode(ISD::UNDEF, VT);
2087 case ISD::SIGN_EXTEND:
2088 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2089 "Invalid SIGN_EXTEND!");
2090 if (Operand.getValueType() == VT) return Operand; // noop extension
2091 assert(Operand.getValueType().bitsLT(VT)
2092 && "Invalid sext node, dst < src!");
2093 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
2094 return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
2096 case ISD::ZERO_EXTEND:
2097 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2098 "Invalid ZERO_EXTEND!");
2099 if (Operand.getValueType() == VT) return Operand; // noop extension
2100 assert(Operand.getValueType().bitsLT(VT)
2101 && "Invalid zext node, dst < src!");
2102 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x)
2103 return getNode(ISD::ZERO_EXTEND, VT, Operand.Val->getOperand(0));
2105 case ISD::ANY_EXTEND:
2106 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2107 "Invalid ANY_EXTEND!");
2108 if (Operand.getValueType() == VT) return Operand; // noop extension
2109 assert(Operand.getValueType().bitsLT(VT)
2110 && "Invalid anyext node, dst < src!");
2111 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND)
2112 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x)
2113 return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
2116 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2117 "Invalid TRUNCATE!");
2118 if (Operand.getValueType() == VT) return Operand; // noop truncate
2119 assert(Operand.getValueType().bitsGT(VT)
2120 && "Invalid truncate node, src < dst!");
2121 if (OpOpcode == ISD::TRUNCATE)
2122 return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
2123 else if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
2124 OpOpcode == ISD::ANY_EXTEND) {
2125 // If the source is smaller than the dest, we still need an extend.
2126 if (Operand.Val->getOperand(0).getValueType().bitsLT(VT))
2127 return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
2128 else if (Operand.Val->getOperand(0).getValueType().bitsGT(VT))
2129 return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
2131 return Operand.Val->getOperand(0);
2134 case ISD::BIT_CONVERT:
2135 // Basic sanity checking.
2136 assert(VT.getSizeInBits() == Operand.getValueType().getSizeInBits()
2137 && "Cannot BIT_CONVERT between types of different sizes!");
2138 if (VT == Operand.getValueType()) return Operand; // noop conversion.
2139 if (OpOpcode == ISD::BIT_CONVERT) // bitconv(bitconv(x)) -> bitconv(x)
2140 return getNode(ISD::BIT_CONVERT, VT, Operand.getOperand(0));
2141 if (OpOpcode == ISD::UNDEF)
2142 return getNode(ISD::UNDEF, VT);
2144 case ISD::SCALAR_TO_VECTOR:
2145 assert(VT.isVector() && !Operand.getValueType().isVector() &&
2146 VT.getVectorElementType() == Operand.getValueType() &&
2147 "Illegal SCALAR_TO_VECTOR node!");
2148 if (OpOpcode == ISD::UNDEF)
2149 return getNode(ISD::UNDEF, VT);
2150 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
2151 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
2152 isa<ConstantSDNode>(Operand.getOperand(1)) &&
2153 Operand.getConstantOperandVal(1) == 0 &&
2154 Operand.getOperand(0).getValueType() == VT)
2155 return Operand.getOperand(0);
2158 if (OpOpcode == ISD::FSUB) // -(X-Y) -> (Y-X)
2159 return getNode(ISD::FSUB, VT, Operand.Val->getOperand(1),
2160 Operand.Val->getOperand(0));
2161 if (OpOpcode == ISD::FNEG) // --X -> X
2162 return Operand.Val->getOperand(0);
2165 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X)
2166 return getNode(ISD::FABS, VT, Operand.Val->getOperand(0));
2171 SDVTList VTs = getVTList(VT);
2172 if (VT != MVT::Flag) { // Don't CSE flag producing nodes
2173 FoldingSetNodeID ID;
2174 SDValue Ops[1] = { Operand };
2175 AddNodeIDNode(ID, Opcode, VTs, Ops, 1);
2177 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2178 return SDValue(E, 0);
2179 N = getAllocator().Allocate<UnarySDNode>();
2180 new (N) UnarySDNode(Opcode, VTs, Operand);
2181 CSEMap.InsertNode(N, IP);
2183 N = getAllocator().Allocate<UnarySDNode>();
2184 new (N) UnarySDNode(Opcode, VTs, Operand);
2187 AllNodes.push_back(N);
2191 return SDValue(N, 0);
2194 SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT,
2195 SDValue N1, SDValue N2) {
2196 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
2197 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
2200 case ISD::TokenFactor:
2201 assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
2202 N2.getValueType() == MVT::Other && "Invalid token factor!");
2203 // Fold trivial token factors.
2204 if (N1.getOpcode() == ISD::EntryToken) return N2;
2205 if (N2.getOpcode() == ISD::EntryToken) return N1;
2208 assert(VT.isInteger() && N1.getValueType() == N2.getValueType() &&
2209 N1.getValueType() == VT && "Binary operator types must match!");
2210 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's
2211 // worth handling here.
2212 if (N2C && N2C->isNullValue())
2214 if (N2C && N2C->isAllOnesValue()) // X & -1 -> X
2221 assert(VT.isInteger() && N1.getValueType() == N2.getValueType() &&
2222 N1.getValueType() == VT && "Binary operator types must match!");
2223 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so
2224 // it's worth handling here.
2225 if (N2C && N2C->isNullValue())
2232 assert(VT.isInteger() && "This operator does not apply to FP types!");
2242 assert(N1.getValueType() == N2.getValueType() &&
2243 N1.getValueType() == VT && "Binary operator types must match!");
2245 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match.
2246 assert(N1.getValueType() == VT &&
2247 N1.getValueType().isFloatingPoint() &&
2248 N2.getValueType().isFloatingPoint() &&
2249 "Invalid FCOPYSIGN!");
2256 assert(VT == N1.getValueType() &&
2257 "Shift operators return type must be the same as their first arg");
2258 assert(VT.isInteger() && N2.getValueType().isInteger() &&
2259 "Shifts only work on integers");
2261 // Always fold shifts of i1 values so the code generator doesn't need to
2262 // handle them. Since we know the size of the shift has to be less than the
2263 // size of the value, the shift/rotate count is guaranteed to be zero.
2267 case ISD::FP_ROUND_INREG: {
2268 MVT EVT = cast<VTSDNode>(N2)->getVT();
2269 assert(VT == N1.getValueType() && "Not an inreg round!");
2270 assert(VT.isFloatingPoint() && EVT.isFloatingPoint() &&
2271 "Cannot FP_ROUND_INREG integer types");
2272 assert(EVT.bitsLE(VT) && "Not rounding down!");
2273 if (cast<VTSDNode>(N2)->getVT() == VT) return N1; // Not actually rounding.
2277 assert(VT.isFloatingPoint() &&
2278 N1.getValueType().isFloatingPoint() &&
2279 VT.bitsLE(N1.getValueType()) &&
2280 isa<ConstantSDNode>(N2) && "Invalid FP_ROUND!");
2281 if (N1.getValueType() == VT) return N1; // noop conversion.
2283 case ISD::AssertSext:
2284 case ISD::AssertZext: {
2285 MVT EVT = cast<VTSDNode>(N2)->getVT();
2286 assert(VT == N1.getValueType() && "Not an inreg extend!");
2287 assert(VT.isInteger() && EVT.isInteger() &&
2288 "Cannot *_EXTEND_INREG FP types");
2289 assert(EVT.bitsLE(VT) && "Not extending!");
2290 if (VT == EVT) return N1; // noop assertion.
2293 case ISD::SIGN_EXTEND_INREG: {
2294 MVT EVT = cast<VTSDNode>(N2)->getVT();
2295 assert(VT == N1.getValueType() && "Not an inreg extend!");
2296 assert(VT.isInteger() && EVT.isInteger() &&
2297 "Cannot *_EXTEND_INREG FP types");
2298 assert(EVT.bitsLE(VT) && "Not extending!");
2299 if (EVT == VT) return N1; // Not actually extending
2302 APInt Val = N1C->getAPIntValue();
2303 unsigned FromBits = cast<VTSDNode>(N2)->getVT().getSizeInBits();
2304 Val <<= Val.getBitWidth()-FromBits;
2305 Val = Val.ashr(Val.getBitWidth()-FromBits);
2306 return getConstant(Val, VT);
2310 case ISD::EXTRACT_VECTOR_ELT:
2311 assert(N2C && "Bad EXTRACT_VECTOR_ELT!");
2313 // EXTRACT_VECTOR_ELT of an UNDEF is an UNDEF.
2314 if (N1.getOpcode() == ISD::UNDEF)
2315 return getNode(ISD::UNDEF, VT);
2317 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
2318 // expanding copies of large vectors from registers.
2319 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
2320 N1.getNumOperands() > 0) {
2322 N1.getOperand(0).getValueType().getVectorNumElements();
2323 return getNode(ISD::EXTRACT_VECTOR_ELT, VT,
2324 N1.getOperand(N2C->getValue() / Factor),
2325 getConstant(N2C->getValue() % Factor, N2.getValueType()));
2328 // EXTRACT_VECTOR_ELT of BUILD_VECTOR is often formed while lowering is
2329 // expanding large vector constants.
2330 if (N1.getOpcode() == ISD::BUILD_VECTOR)
2331 return N1.getOperand(N2C->getValue());
2333 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
2334 // operations are lowered to scalars.
2335 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT)
2336 if (ConstantSDNode *IEC = dyn_cast<ConstantSDNode>(N1.getOperand(2))) {
2338 return N1.getOperand(1);
2340 return getNode(ISD::EXTRACT_VECTOR_ELT, VT, N1.getOperand(0), N2);
2343 case ISD::EXTRACT_ELEMENT:
2344 assert(N2C && (unsigned)N2C->getValue() < 2 && "Bad EXTRACT_ELEMENT!");
2345 assert(!N1.getValueType().isVector() && !VT.isVector() &&
2346 (N1.getValueType().isInteger() == VT.isInteger()) &&
2347 "Wrong types for EXTRACT_ELEMENT!");
2349 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
2350 // 64-bit integers into 32-bit parts. Instead of building the extract of
2351 // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
2352 if (N1.getOpcode() == ISD::BUILD_PAIR)
2353 return N1.getOperand(N2C->getValue());
2355 // EXTRACT_ELEMENT of a constant int is also very common.
2356 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2357 unsigned ElementSize = VT.getSizeInBits();
2358 unsigned Shift = ElementSize * N2C->getValue();
2359 APInt ShiftedVal = C->getAPIntValue().lshr(Shift);
2360 return getConstant(ShiftedVal.trunc(ElementSize), VT);
2363 case ISD::EXTRACT_SUBVECTOR:
2364 if (N1.getValueType() == VT) // Trivial extraction.
2371 const APInt &C1 = N1C->getAPIntValue(), &C2 = N2C->getAPIntValue();
2373 case ISD::ADD: return getConstant(C1 + C2, VT);
2374 case ISD::SUB: return getConstant(C1 - C2, VT);
2375 case ISD::MUL: return getConstant(C1 * C2, VT);
2377 if (C2.getBoolValue()) return getConstant(C1.udiv(C2), VT);
2380 if (C2.getBoolValue()) return getConstant(C1.urem(C2), VT);
2383 if (C2.getBoolValue()) return getConstant(C1.sdiv(C2), VT);
2386 if (C2.getBoolValue()) return getConstant(C1.srem(C2), VT);
2388 case ISD::AND : return getConstant(C1 & C2, VT);
2389 case ISD::OR : return getConstant(C1 | C2, VT);
2390 case ISD::XOR : return getConstant(C1 ^ C2, VT);
2391 case ISD::SHL : return getConstant(C1 << C2, VT);
2392 case ISD::SRL : return getConstant(C1.lshr(C2), VT);
2393 case ISD::SRA : return getConstant(C1.ashr(C2), VT);
2394 case ISD::ROTL : return getConstant(C1.rotl(C2), VT);
2395 case ISD::ROTR : return getConstant(C1.rotr(C2), VT);
2398 } else { // Cannonicalize constant to RHS if commutative
2399 if (isCommutativeBinOp(Opcode)) {
2400 std::swap(N1C, N2C);
2406 // Constant fold FP operations.
2407 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1.Val);
2408 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2.Val);
2410 if (!N2CFP && isCommutativeBinOp(Opcode)) {
2411 // Cannonicalize constant to RHS if commutative
2412 std::swap(N1CFP, N2CFP);
2414 } else if (N2CFP && VT != MVT::ppcf128) {
2415 APFloat V1 = N1CFP->getValueAPF(), V2 = N2CFP->getValueAPF();
2416 APFloat::opStatus s;
2419 s = V1.add(V2, APFloat::rmNearestTiesToEven);
2420 if (s != APFloat::opInvalidOp)
2421 return getConstantFP(V1, VT);
2424 s = V1.subtract(V2, APFloat::rmNearestTiesToEven);
2425 if (s!=APFloat::opInvalidOp)
2426 return getConstantFP(V1, VT);
2429 s = V1.multiply(V2, APFloat::rmNearestTiesToEven);
2430 if (s!=APFloat::opInvalidOp)
2431 return getConstantFP(V1, VT);
2434 s = V1.divide(V2, APFloat::rmNearestTiesToEven);
2435 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2436 return getConstantFP(V1, VT);
2439 s = V1.mod(V2, APFloat::rmNearestTiesToEven);
2440 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2441 return getConstantFP(V1, VT);
2443 case ISD::FCOPYSIGN:
2445 return getConstantFP(V1, VT);
2451 // Canonicalize an UNDEF to the RHS, even over a constant.
2452 if (N1.getOpcode() == ISD::UNDEF) {
2453 if (isCommutativeBinOp(Opcode)) {
2457 case ISD::FP_ROUND_INREG:
2458 case ISD::SIGN_EXTEND_INREG:
2464 return N1; // fold op(undef, arg2) -> undef
2472 return getConstant(0, VT); // fold op(undef, arg2) -> 0
2473 // For vectors, we can't easily build an all zero vector, just return
2480 // Fold a bunch of operators when the RHS is undef.
2481 if (N2.getOpcode() == ISD::UNDEF) {
2484 if (N1.getOpcode() == ISD::UNDEF)
2485 // Handle undef ^ undef -> 0 special case. This is a common
2487 return getConstant(0, VT);
2502 return N2; // fold op(arg1, undef) -> undef
2508 return getConstant(0, VT); // fold op(arg1, undef) -> 0
2509 // For vectors, we can't easily build an all zero vector, just return
2514 return getConstant(VT.getIntegerVTBitMask(), VT);
2515 // For vectors, we can't easily build an all one vector, just return
2523 // Memoize this node if possible.
2525 SDVTList VTs = getVTList(VT);
2526 if (VT != MVT::Flag) {
2527 SDValue Ops[] = { N1, N2 };
2528 FoldingSetNodeID ID;
2529 AddNodeIDNode(ID, Opcode, VTs, Ops, 2);
2531 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2532 return SDValue(E, 0);
2533 N = getAllocator().Allocate<BinarySDNode>();
2534 new (N) BinarySDNode(Opcode, VTs, N1, N2);
2535 CSEMap.InsertNode(N, IP);
2537 N = getAllocator().Allocate<BinarySDNode>();
2538 new (N) BinarySDNode(Opcode, VTs, N1, N2);
2541 AllNodes.push_back(N);
2545 return SDValue(N, 0);
2548 SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT,
2549 SDValue N1, SDValue N2, SDValue N3) {
2550 // Perform various simplifications.
2551 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
2552 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
2555 // Use FoldSetCC to simplify SETCC's.
2556 SDValue Simp = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get());
2557 if (Simp.Val) return Simp;
2562 if (N1C->getValue())
2563 return N2; // select true, X, Y -> X
2565 return N3; // select false, X, Y -> Y
2568 if (N2 == N3) return N2; // select C, X, X -> X
2572 if (N2C->getValue()) // Unconditional branch
2573 return getNode(ISD::BR, MVT::Other, N1, N3);
2575 return N1; // Never-taken branch
2578 case ISD::VECTOR_SHUFFLE:
2579 assert(VT == N1.getValueType() && VT == N2.getValueType() &&
2580 VT.isVector() && N3.getValueType().isVector() &&
2581 N3.getOpcode() == ISD::BUILD_VECTOR &&
2582 VT.getVectorNumElements() == N3.getNumOperands() &&
2583 "Illegal VECTOR_SHUFFLE node!");
2585 case ISD::BIT_CONVERT:
2586 // Fold bit_convert nodes from a type to themselves.
2587 if (N1.getValueType() == VT)
2592 // Memoize node if it doesn't produce a flag.
2594 SDVTList VTs = getVTList(VT);
2595 if (VT != MVT::Flag) {
2596 SDValue Ops[] = { N1, N2, N3 };
2597 FoldingSetNodeID ID;
2598 AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
2600 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2601 return SDValue(E, 0);
2602 N = getAllocator().Allocate<TernarySDNode>();
2603 new (N) TernarySDNode(Opcode, VTs, N1, N2, N3);
2604 CSEMap.InsertNode(N, IP);
2606 N = getAllocator().Allocate<TernarySDNode>();
2607 new (N) TernarySDNode(Opcode, VTs, N1, N2, N3);
2609 AllNodes.push_back(N);
2613 return SDValue(N, 0);
2616 SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT,
2617 SDValue N1, SDValue N2, SDValue N3,
2619 SDValue Ops[] = { N1, N2, N3, N4 };
2620 return getNode(Opcode, VT, Ops, 4);
2623 SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT,
2624 SDValue N1, SDValue N2, SDValue N3,
2625 SDValue N4, SDValue N5) {
2626 SDValue Ops[] = { N1, N2, N3, N4, N5 };
2627 return getNode(Opcode, VT, Ops, 5);
2630 /// getMemsetValue - Vectorized representation of the memset value
2632 static SDValue getMemsetValue(SDValue Value, MVT VT, SelectionDAG &DAG) {
2633 unsigned NumBits = VT.isVector() ?
2634 VT.getVectorElementType().getSizeInBits() : VT.getSizeInBits();
2635 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
2636 APInt Val = APInt(NumBits, C->getValue() & 255);
2638 for (unsigned i = NumBits; i > 8; i >>= 1) {
2639 Val = (Val << Shift) | Val;
2643 return DAG.getConstant(Val, VT);
2644 return DAG.getConstantFP(APFloat(Val), VT);
2647 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
2649 for (unsigned i = NumBits; i > 8; i >>= 1) {
2650 Value = DAG.getNode(ISD::OR, VT,
2651 DAG.getNode(ISD::SHL, VT, Value,
2652 DAG.getConstant(Shift, MVT::i8)), Value);
2659 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
2660 /// used when a memcpy is turned into a memset when the source is a constant
2662 static SDValue getMemsetStringVal(MVT VT, SelectionDAG &DAG,
2663 const TargetLowering &TLI,
2664 std::string &Str, unsigned Offset) {
2665 // Handle vector with all elements zero.
2668 return DAG.getConstant(0, VT);
2669 unsigned NumElts = VT.getVectorNumElements();
2670 MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
2671 return DAG.getNode(ISD::BIT_CONVERT, VT,
2672 DAG.getConstant(0, MVT::getVectorVT(EltVT, NumElts)));
2675 assert(!VT.isVector() && "Can't handle vector type here!");
2676 unsigned NumBits = VT.getSizeInBits();
2677 unsigned MSB = NumBits / 8;
2679 if (TLI.isLittleEndian())
2680 Offset = Offset + MSB - 1;
2681 for (unsigned i = 0; i != MSB; ++i) {
2682 Val = (Val << 8) | (unsigned char)Str[Offset];
2683 Offset += TLI.isLittleEndian() ? -1 : 1;
2685 return DAG.getConstant(Val, VT);
2688 /// getMemBasePlusOffset - Returns base and offset node for the
2690 static SDValue getMemBasePlusOffset(SDValue Base, unsigned Offset,
2691 SelectionDAG &DAG) {
2692 MVT VT = Base.getValueType();
2693 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
2696 /// isMemSrcFromString - Returns true if memcpy source is a string constant.
2698 static bool isMemSrcFromString(SDValue Src, std::string &Str) {
2699 unsigned SrcDelta = 0;
2700 GlobalAddressSDNode *G = NULL;
2701 if (Src.getOpcode() == ISD::GlobalAddress)
2702 G = cast<GlobalAddressSDNode>(Src);
2703 else if (Src.getOpcode() == ISD::ADD &&
2704 Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
2705 Src.getOperand(1).getOpcode() == ISD::Constant) {
2706 G = cast<GlobalAddressSDNode>(Src.getOperand(0));
2707 SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getValue();
2712 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
2713 if (GV && GetConstantStringInfo(GV, Str, SrcDelta, false))
2719 /// MeetsMaxMemopRequirement - Determines if the number of memory ops required
2720 /// to replace the memset / memcpy is below the threshold. It also returns the
2721 /// types of the sequence of memory ops to perform memset / memcpy.
2723 bool MeetsMaxMemopRequirement(std::vector<MVT> &MemOps,
2724 SDValue Dst, SDValue Src,
2725 unsigned Limit, uint64_t Size, unsigned &Align,
2726 std::string &Str, bool &isSrcStr,
2728 const TargetLowering &TLI) {
2729 isSrcStr = isMemSrcFromString(Src, Str);
2730 bool isSrcConst = isa<ConstantSDNode>(Src);
2731 bool AllowUnalign = TLI.allowsUnalignedMemoryAccesses();
2732 MVT VT= TLI.getOptimalMemOpType(Size, Align, isSrcConst, isSrcStr);
2733 if (VT != MVT::iAny) {
2734 unsigned NewAlign = (unsigned)
2735 TLI.getTargetData()->getABITypeAlignment(VT.getTypeForMVT());
2736 // If source is a string constant, this will require an unaligned load.
2737 if (NewAlign > Align && (isSrcConst || AllowUnalign)) {
2738 if (Dst.getOpcode() != ISD::FrameIndex) {
2739 // Can't change destination alignment. It requires a unaligned store.
2743 int FI = cast<FrameIndexSDNode>(Dst)->getIndex();
2744 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2745 if (MFI->isFixedObjectIndex(FI)) {
2746 // Can't change destination alignment. It requires a unaligned store.
2750 // Give the stack frame object a larger alignment if needed.
2751 if (MFI->getObjectAlignment(FI) < NewAlign)
2752 MFI->setObjectAlignment(FI, NewAlign);
2759 if (VT == MVT::iAny) {
2763 switch (Align & 7) {
2764 case 0: VT = MVT::i64; break;
2765 case 4: VT = MVT::i32; break;
2766 case 2: VT = MVT::i16; break;
2767 default: VT = MVT::i8; break;
2772 while (!TLI.isTypeLegal(LVT))
2773 LVT = (MVT::SimpleValueType)(LVT.getSimpleVT() - 1);
2774 assert(LVT.isInteger());
2780 unsigned NumMemOps = 0;
2782 unsigned VTSize = VT.getSizeInBits() / 8;
2783 while (VTSize > Size) {
2784 // For now, only use non-vector load / store's for the left-over pieces.
2785 if (VT.isVector()) {
2787 while (!TLI.isTypeLegal(VT))
2788 VT = (MVT::SimpleValueType)(VT.getSimpleVT() - 1);
2789 VTSize = VT.getSizeInBits() / 8;
2791 VT = (MVT::SimpleValueType)(VT.getSimpleVT() - 1);
2796 if (++NumMemOps > Limit)
2798 MemOps.push_back(VT);
2805 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG,
2806 SDValue Chain, SDValue Dst,
2807 SDValue Src, uint64_t Size,
2808 unsigned Align, bool AlwaysInline,
2809 const Value *DstSV, uint64_t DstSVOff,
2810 const Value *SrcSV, uint64_t SrcSVOff){
2811 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2813 // Expand memcpy to a series of load and store ops if the size operand falls
2814 // below a certain threshold.
2815 std::vector<MVT> MemOps;
2816 uint64_t Limit = -1;
2818 Limit = TLI.getMaxStoresPerMemcpy();
2819 unsigned DstAlign = Align; // Destination alignment can change.
2822 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, Limit, Size, DstAlign,
2823 Str, CopyFromStr, DAG, TLI))
2827 bool isZeroStr = CopyFromStr && Str.empty();
2828 SmallVector<SDValue, 8> OutChains;
2829 unsigned NumMemOps = MemOps.size();
2830 uint64_t SrcOff = 0, DstOff = 0;
2831 for (unsigned i = 0; i < NumMemOps; i++) {
2833 unsigned VTSize = VT.getSizeInBits() / 8;
2834 SDValue Value, Store;
2836 if (CopyFromStr && (isZeroStr || !VT.isVector())) {
2837 // It's unlikely a store of a vector immediate can be done in a single
2838 // instruction. It would require a load from a constantpool first.
2839 // We also handle store a vector with all zero's.
2840 // FIXME: Handle other cases where store of vector immediate is done in
2841 // a single instruction.
2842 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
2843 Store = DAG.getStore(Chain, Value,
2844 getMemBasePlusOffset(Dst, DstOff, DAG),
2845 DstSV, DstSVOff + DstOff, false, DstAlign);
2847 Value = DAG.getLoad(VT, Chain,
2848 getMemBasePlusOffset(Src, SrcOff, DAG),
2849 SrcSV, SrcSVOff + SrcOff, false, Align);
2850 Store = DAG.getStore(Chain, Value,
2851 getMemBasePlusOffset(Dst, DstOff, DAG),
2852 DstSV, DstSVOff + DstOff, false, DstAlign);
2854 OutChains.push_back(Store);
2859 return DAG.getNode(ISD::TokenFactor, MVT::Other,
2860 &OutChains[0], OutChains.size());
2863 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG,
2864 SDValue Chain, SDValue Dst,
2865 SDValue Src, uint64_t Size,
2866 unsigned Align, bool AlwaysInline,
2867 const Value *DstSV, uint64_t DstSVOff,
2868 const Value *SrcSV, uint64_t SrcSVOff){
2869 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2871 // Expand memmove to a series of load and store ops if the size operand falls
2872 // below a certain threshold.
2873 std::vector<MVT> MemOps;
2874 uint64_t Limit = -1;
2876 Limit = TLI.getMaxStoresPerMemmove();
2877 unsigned DstAlign = Align; // Destination alignment can change.
2880 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, Limit, Size, DstAlign,
2881 Str, CopyFromStr, DAG, TLI))
2884 uint64_t SrcOff = 0, DstOff = 0;
2886 SmallVector<SDValue, 8> LoadValues;
2887 SmallVector<SDValue, 8> LoadChains;
2888 SmallVector<SDValue, 8> OutChains;
2889 unsigned NumMemOps = MemOps.size();
2890 for (unsigned i = 0; i < NumMemOps; i++) {
2892 unsigned VTSize = VT.getSizeInBits() / 8;
2893 SDValue Value, Store;
2895 Value = DAG.getLoad(VT, Chain,
2896 getMemBasePlusOffset(Src, SrcOff, DAG),
2897 SrcSV, SrcSVOff + SrcOff, false, Align);
2898 LoadValues.push_back(Value);
2899 LoadChains.push_back(Value.getValue(1));
2902 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2903 &LoadChains[0], LoadChains.size());
2905 for (unsigned i = 0; i < NumMemOps; i++) {
2907 unsigned VTSize = VT.getSizeInBits() / 8;
2908 SDValue Value, Store;
2910 Store = DAG.getStore(Chain, LoadValues[i],
2911 getMemBasePlusOffset(Dst, DstOff, DAG),
2912 DstSV, DstSVOff + DstOff, false, DstAlign);
2913 OutChains.push_back(Store);
2917 return DAG.getNode(ISD::TokenFactor, MVT::Other,
2918 &OutChains[0], OutChains.size());
2921 static SDValue getMemsetStores(SelectionDAG &DAG,
2922 SDValue Chain, SDValue Dst,
2923 SDValue Src, uint64_t Size,
2925 const Value *DstSV, uint64_t DstSVOff) {
2926 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2928 // Expand memset to a series of load/store ops if the size operand
2929 // falls below a certain threshold.
2930 std::vector<MVT> MemOps;
2933 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, TLI.getMaxStoresPerMemset(),
2934 Size, Align, Str, CopyFromStr, DAG, TLI))
2937 SmallVector<SDValue, 8> OutChains;
2938 uint64_t DstOff = 0;
2940 unsigned NumMemOps = MemOps.size();
2941 for (unsigned i = 0; i < NumMemOps; i++) {
2943 unsigned VTSize = VT.getSizeInBits() / 8;
2944 SDValue Value = getMemsetValue(Src, VT, DAG);
2945 SDValue Store = DAG.getStore(Chain, Value,
2946 getMemBasePlusOffset(Dst, DstOff, DAG),
2947 DstSV, DstSVOff + DstOff);
2948 OutChains.push_back(Store);
2952 return DAG.getNode(ISD::TokenFactor, MVT::Other,
2953 &OutChains[0], OutChains.size());
2956 SDValue SelectionDAG::getMemcpy(SDValue Chain, SDValue Dst,
2957 SDValue Src, SDValue Size,
2958 unsigned Align, bool AlwaysInline,
2959 const Value *DstSV, uint64_t DstSVOff,
2960 const Value *SrcSV, uint64_t SrcSVOff) {
2962 // Check to see if we should lower the memcpy to loads and stores first.
2963 // For cases within the target-specified limits, this is the best choice.
2964 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
2966 // Memcpy with size zero? Just return the original chain.
2967 if (ConstantSize->isNullValue())
2971 getMemcpyLoadsAndStores(*this, Chain, Dst, Src, ConstantSize->getValue(),
2972 Align, false, DstSV, DstSVOff, SrcSV, SrcSVOff);
2977 // Then check to see if we should lower the memcpy with target-specific
2978 // code. If the target chooses to do this, this is the next best.
2980 TLI.EmitTargetCodeForMemcpy(*this, Chain, Dst, Src, Size, Align,
2982 DstSV, DstSVOff, SrcSV, SrcSVOff);
2986 // If we really need inline code and the target declined to provide it,
2987 // use a (potentially long) sequence of loads and stores.
2989 assert(ConstantSize && "AlwaysInline requires a constant size!");
2990 return getMemcpyLoadsAndStores(*this, Chain, Dst, Src,
2991 ConstantSize->getValue(), Align, true,
2992 DstSV, DstSVOff, SrcSV, SrcSVOff);
2995 // Emit a library call.
2996 TargetLowering::ArgListTy Args;
2997 TargetLowering::ArgListEntry Entry;
2998 Entry.Ty = TLI.getTargetData()->getIntPtrType();
2999 Entry.Node = Dst; Args.push_back(Entry);
3000 Entry.Node = Src; Args.push_back(Entry);
3001 Entry.Node = Size; Args.push_back(Entry);
3002 std::pair<SDValue,SDValue> CallResult =
3003 TLI.LowerCallTo(Chain, Type::VoidTy,
3004 false, false, false, CallingConv::C, false,
3005 getExternalSymbol("memcpy", TLI.getPointerTy()),
3007 return CallResult.second;
3010 SDValue SelectionDAG::getMemmove(SDValue Chain, SDValue Dst,
3011 SDValue Src, SDValue Size,
3013 const Value *DstSV, uint64_t DstSVOff,
3014 const Value *SrcSV, uint64_t SrcSVOff) {
3016 // Check to see if we should lower the memmove to loads and stores first.
3017 // For cases within the target-specified limits, this is the best choice.
3018 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
3020 // Memmove with size zero? Just return the original chain.
3021 if (ConstantSize->isNullValue())
3025 getMemmoveLoadsAndStores(*this, Chain, Dst, Src, ConstantSize->getValue(),
3026 Align, false, DstSV, DstSVOff, SrcSV, SrcSVOff);
3031 // Then check to see if we should lower the memmove with target-specific
3032 // code. If the target chooses to do this, this is the next best.
3034 TLI.EmitTargetCodeForMemmove(*this, Chain, Dst, Src, Size, Align,
3035 DstSV, DstSVOff, SrcSV, SrcSVOff);
3039 // Emit a library call.
3040 TargetLowering::ArgListTy Args;
3041 TargetLowering::ArgListEntry Entry;
3042 Entry.Ty = TLI.getTargetData()->getIntPtrType();
3043 Entry.Node = Dst; Args.push_back(Entry);
3044 Entry.Node = Src; Args.push_back(Entry);
3045 Entry.Node = Size; Args.push_back(Entry);
3046 std::pair<SDValue,SDValue> CallResult =
3047 TLI.LowerCallTo(Chain, Type::VoidTy,
3048 false, false, false, CallingConv::C, false,
3049 getExternalSymbol("memmove", TLI.getPointerTy()),
3051 return CallResult.second;
3054 SDValue SelectionDAG::getMemset(SDValue Chain, SDValue Dst,
3055 SDValue Src, SDValue Size,
3057 const Value *DstSV, uint64_t DstSVOff) {
3059 // Check to see if we should lower the memset to stores first.
3060 // For cases within the target-specified limits, this is the best choice.
3061 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
3063 // Memset with size zero? Just return the original chain.
3064 if (ConstantSize->isNullValue())
3068 getMemsetStores(*this, Chain, Dst, Src, ConstantSize->getValue(), Align,
3074 // Then check to see if we should lower the memset with target-specific
3075 // code. If the target chooses to do this, this is the next best.
3077 TLI.EmitTargetCodeForMemset(*this, Chain, Dst, Src, Size, Align,
3082 // Emit a library call.
3083 const Type *IntPtrTy = TLI.getTargetData()->getIntPtrType();
3084 TargetLowering::ArgListTy Args;
3085 TargetLowering::ArgListEntry Entry;
3086 Entry.Node = Dst; Entry.Ty = IntPtrTy;
3087 Args.push_back(Entry);
3088 // Extend or truncate the argument to be an i32 value for the call.
3089 if (Src.getValueType().bitsGT(MVT::i32))
3090 Src = getNode(ISD::TRUNCATE, MVT::i32, Src);
3092 Src = getNode(ISD::ZERO_EXTEND, MVT::i32, Src);
3093 Entry.Node = Src; Entry.Ty = Type::Int32Ty; Entry.isSExt = true;
3094 Args.push_back(Entry);
3095 Entry.Node = Size; Entry.Ty = IntPtrTy; Entry.isSExt = false;
3096 Args.push_back(Entry);
3097 std::pair<SDValue,SDValue> CallResult =
3098 TLI.LowerCallTo(Chain, Type::VoidTy,
3099 false, false, false, CallingConv::C, false,
3100 getExternalSymbol("memset", TLI.getPointerTy()),
3102 return CallResult.second;
3105 SDValue SelectionDAG::getAtomic(unsigned Opcode, SDValue Chain,
3106 SDValue Ptr, SDValue Cmp,
3107 SDValue Swp, const Value* PtrVal,
3108 unsigned Alignment) {
3109 assert(Opcode == ISD::ATOMIC_CMP_SWAP && "Invalid Atomic Op");
3110 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
3112 MVT VT = Cmp.getValueType();
3114 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3115 Alignment = getMVTAlignment(VT);
3117 SDVTList VTs = getVTList(VT, MVT::Other);
3118 FoldingSetNodeID ID;
3119 SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
3120 AddNodeIDNode(ID, Opcode, VTs, Ops, 4);
3122 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3123 return SDValue(E, 0);
3124 SDNode* N = getAllocator().Allocate<AtomicSDNode>();
3125 new (N) AtomicSDNode(Opcode, VTs, Chain, Ptr, Cmp, Swp, PtrVal, Alignment);
3126 CSEMap.InsertNode(N, IP);
3127 AllNodes.push_back(N);
3128 return SDValue(N, 0);
3131 SDValue SelectionDAG::getAtomic(unsigned Opcode, SDValue Chain,
3132 SDValue Ptr, SDValue Val,
3133 const Value* PtrVal,
3134 unsigned Alignment) {
3135 assert(( Opcode == ISD::ATOMIC_LOAD_ADD || Opcode == ISD::ATOMIC_LOAD_SUB
3136 || Opcode == ISD::ATOMIC_SWAP || Opcode == ISD::ATOMIC_LOAD_AND
3137 || Opcode == ISD::ATOMIC_LOAD_OR || Opcode == ISD::ATOMIC_LOAD_XOR
3138 || Opcode == ISD::ATOMIC_LOAD_NAND
3139 || Opcode == ISD::ATOMIC_LOAD_MIN || Opcode == ISD::ATOMIC_LOAD_MAX
3140 || Opcode == ISD::ATOMIC_LOAD_UMIN || Opcode == ISD::ATOMIC_LOAD_UMAX)
3141 && "Invalid Atomic Op");
3143 MVT VT = Val.getValueType();
3145 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3146 Alignment = getMVTAlignment(VT);
3148 SDVTList VTs = getVTList(VT, MVT::Other);
3149 FoldingSetNodeID ID;
3150 SDValue Ops[] = {Chain, Ptr, Val};
3151 AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
3153 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3154 return SDValue(E, 0);
3155 SDNode* N = getAllocator().Allocate<AtomicSDNode>();
3156 new (N) AtomicSDNode(Opcode, VTs, Chain, Ptr, Val, PtrVal, Alignment);
3157 CSEMap.InsertNode(N, IP);
3158 AllNodes.push_back(N);
3159 return SDValue(N, 0);
3162 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
3163 /// Allowed to return something different (and simpler) if Simplify is true.
3164 SDValue SelectionDAG::getMergeValues(const SDValue *Ops, unsigned NumOps,
3166 if (Simplify && NumOps == 1)
3169 SmallVector<MVT, 4> VTs;
3170 VTs.reserve(NumOps);
3171 for (unsigned i = 0; i < NumOps; ++i)
3172 VTs.push_back(Ops[i].getValueType());
3173 return getNode(ISD::MERGE_VALUES, getVTList(&VTs[0], NumOps), Ops, NumOps);
3177 SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
3178 MVT VT, SDValue Chain,
3179 SDValue Ptr, SDValue Offset,
3180 const Value *SV, int SVOffset, MVT EVT,
3181 bool isVolatile, unsigned Alignment) {
3182 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3183 Alignment = getMVTAlignment(VT);
3186 ExtType = ISD::NON_EXTLOAD;
3187 } else if (ExtType == ISD::NON_EXTLOAD) {
3188 assert(VT == EVT && "Non-extending load from different memory type!");
3192 assert(EVT == VT.getVectorElementType() && "Invalid vector extload!");
3194 assert(EVT.bitsLT(VT) &&
3195 "Should only be an extending load, not truncating!");
3196 assert((ExtType == ISD::EXTLOAD || VT.isInteger()) &&
3197 "Cannot sign/zero extend a FP/Vector load!");
3198 assert(VT.isInteger() == EVT.isInteger() &&
3199 "Cannot convert from FP to Int or Int -> FP!");
3202 bool Indexed = AM != ISD::UNINDEXED;
3203 assert((Indexed || Offset.getOpcode() == ISD::UNDEF) &&
3204 "Unindexed load with an offset!");
3206 SDVTList VTs = Indexed ?
3207 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
3208 SDValue Ops[] = { Chain, Ptr, Offset };
3209 FoldingSetNodeID ID;
3210 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops, 3);
3212 ID.AddInteger(ExtType);
3213 ID.AddInteger(EVT.getRawBits());
3214 ID.AddInteger(Alignment);
3215 ID.AddInteger(isVolatile);
3217 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3218 return SDValue(E, 0);
3219 SDNode *N = getAllocator().Allocate<LoadSDNode>();
3220 new (N) LoadSDNode(Ops, VTs, AM, ExtType, EVT, SV, SVOffset,
3221 Alignment, isVolatile);
3222 CSEMap.InsertNode(N, IP);
3223 AllNodes.push_back(N);
3224 return SDValue(N, 0);
3227 SDValue SelectionDAG::getLoad(MVT VT,
3228 SDValue Chain, SDValue Ptr,
3229 const Value *SV, int SVOffset,
3230 bool isVolatile, unsigned Alignment) {
3231 SDValue Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3232 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, Chain, Ptr, Undef,
3233 SV, SVOffset, VT, isVolatile, Alignment);
3236 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, MVT VT,
3237 SDValue Chain, SDValue Ptr,
3239 int SVOffset, MVT EVT,
3240 bool isVolatile, unsigned Alignment) {
3241 SDValue Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3242 return getLoad(ISD::UNINDEXED, ExtType, VT, Chain, Ptr, Undef,
3243 SV, SVOffset, EVT, isVolatile, Alignment);
3247 SelectionDAG::getIndexedLoad(SDValue OrigLoad, SDValue Base,
3248 SDValue Offset, ISD::MemIndexedMode AM) {
3249 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
3250 assert(LD->getOffset().getOpcode() == ISD::UNDEF &&
3251 "Load is already a indexed load!");
3252 return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(),
3253 LD->getChain(), Base, Offset, LD->getSrcValue(),
3254 LD->getSrcValueOffset(), LD->getMemoryVT(),
3255 LD->isVolatile(), LD->getAlignment());
3258 SDValue SelectionDAG::getStore(SDValue Chain, SDValue Val,
3259 SDValue Ptr, const Value *SV, int SVOffset,
3260 bool isVolatile, unsigned Alignment) {
3261 MVT VT = Val.getValueType();
3263 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3264 Alignment = getMVTAlignment(VT);
3266 SDVTList VTs = getVTList(MVT::Other);
3267 SDValue Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3268 SDValue Ops[] = { Chain, Val, Ptr, Undef };
3269 FoldingSetNodeID ID;
3270 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3271 ID.AddInteger(ISD::UNINDEXED);
3272 ID.AddInteger(false);
3273 ID.AddInteger(VT.getRawBits());
3274 ID.AddInteger(Alignment);
3275 ID.AddInteger(isVolatile);
3277 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3278 return SDValue(E, 0);
3279 SDNode *N = getAllocator().Allocate<StoreSDNode>();
3280 new (N) StoreSDNode(Ops, VTs, ISD::UNINDEXED, false,
3281 VT, SV, SVOffset, Alignment, isVolatile);
3282 CSEMap.InsertNode(N, IP);
3283 AllNodes.push_back(N);
3284 return SDValue(N, 0);
3287 SDValue SelectionDAG::getTruncStore(SDValue Chain, SDValue Val,
3288 SDValue Ptr, const Value *SV,
3289 int SVOffset, MVT SVT,
3290 bool isVolatile, unsigned Alignment) {
3291 MVT VT = Val.getValueType();
3294 return getStore(Chain, Val, Ptr, SV, SVOffset, isVolatile, Alignment);
3296 assert(VT.bitsGT(SVT) && "Not a truncation?");
3297 assert(VT.isInteger() == SVT.isInteger() &&
3298 "Can't do FP-INT conversion!");
3300 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3301 Alignment = getMVTAlignment(VT);
3303 SDVTList VTs = getVTList(MVT::Other);
3304 SDValue Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3305 SDValue Ops[] = { Chain, Val, Ptr, Undef };
3306 FoldingSetNodeID ID;
3307 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3308 ID.AddInteger(ISD::UNINDEXED);
3310 ID.AddInteger(SVT.getRawBits());
3311 ID.AddInteger(Alignment);
3312 ID.AddInteger(isVolatile);
3314 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3315 return SDValue(E, 0);
3316 SDNode *N = getAllocator().Allocate<StoreSDNode>();
3317 new (N) StoreSDNode(Ops, VTs, ISD::UNINDEXED, true,
3318 SVT, SV, SVOffset, Alignment, isVolatile);
3319 CSEMap.InsertNode(N, IP);
3320 AllNodes.push_back(N);
3321 return SDValue(N, 0);
3325 SelectionDAG::getIndexedStore(SDValue OrigStore, SDValue Base,
3326 SDValue Offset, ISD::MemIndexedMode AM) {
3327 StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
3328 assert(ST->getOffset().getOpcode() == ISD::UNDEF &&
3329 "Store is already a indexed store!");
3330 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
3331 SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
3332 FoldingSetNodeID ID;
3333 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3335 ID.AddInteger(ST->isTruncatingStore());
3336 ID.AddInteger(ST->getMemoryVT().getRawBits());
3337 ID.AddInteger(ST->getAlignment());
3338 ID.AddInteger(ST->isVolatile());
3340 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3341 return SDValue(E, 0);
3342 SDNode *N = getAllocator().Allocate<StoreSDNode>();
3343 new (N) StoreSDNode(Ops, VTs, AM,
3344 ST->isTruncatingStore(), ST->getMemoryVT(),
3345 ST->getSrcValue(), ST->getSrcValueOffset(),
3346 ST->getAlignment(), ST->isVolatile());
3347 CSEMap.InsertNode(N, IP);
3348 AllNodes.push_back(N);
3349 return SDValue(N, 0);
3352 SDValue SelectionDAG::getVAArg(MVT VT,
3353 SDValue Chain, SDValue Ptr,
3355 SDValue Ops[] = { Chain, Ptr, SV };
3356 return getNode(ISD::VAARG, getVTList(VT, MVT::Other), Ops, 3);
3359 SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT,
3360 const SDUse *Ops, unsigned NumOps) {
3362 case 0: return getNode(Opcode, VT);
3363 case 1: return getNode(Opcode, VT, Ops[0]);
3364 case 2: return getNode(Opcode, VT, Ops[0], Ops[1]);
3365 case 3: return getNode(Opcode, VT, Ops[0], Ops[1], Ops[2]);
3369 // Copy from an SDUse array into an SDValue array for use with
3370 // the regular getNode logic.
3371 SmallVector<SDValue, 8> NewOps(Ops, Ops + NumOps);
3372 return getNode(Opcode, VT, &NewOps[0], NumOps);
3375 SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT,
3376 const SDValue *Ops, unsigned NumOps) {
3378 case 0: return getNode(Opcode, VT);
3379 case 1: return getNode(Opcode, VT, Ops[0]);
3380 case 2: return getNode(Opcode, VT, Ops[0], Ops[1]);
3381 case 3: return getNode(Opcode, VT, Ops[0], Ops[1], Ops[2]);
3387 case ISD::SELECT_CC: {
3388 assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
3389 assert(Ops[0].getValueType() == Ops[1].getValueType() &&
3390 "LHS and RHS of condition must have same type!");
3391 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
3392 "True and False arms of SelectCC must have same type!");
3393 assert(Ops[2].getValueType() == VT &&
3394 "select_cc node must be of same type as true and false value!");
3398 assert(NumOps == 5 && "BR_CC takes 5 operands!");
3399 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
3400 "LHS/RHS of comparison should match types!");
3407 SDVTList VTs = getVTList(VT);
3408 if (VT != MVT::Flag) {
3409 FoldingSetNodeID ID;
3410 AddNodeIDNode(ID, Opcode, VTs, Ops, NumOps);
3412 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3413 return SDValue(E, 0);
3414 N = getAllocator().Allocate<SDNode>();
3415 new (N) SDNode(Opcode, VTs, Ops, NumOps);
3416 CSEMap.InsertNode(N, IP);
3418 N = getAllocator().Allocate<SDNode>();
3419 new (N) SDNode(Opcode, VTs, Ops, NumOps);
3421 AllNodes.push_back(N);
3425 return SDValue(N, 0);
3428 SDValue SelectionDAG::getNode(unsigned Opcode,
3429 const std::vector<MVT> &ResultTys,
3430 const SDValue *Ops, unsigned NumOps) {
3431 return getNode(Opcode, getNodeValueTypes(ResultTys), ResultTys.size(),
3435 SDValue SelectionDAG::getNode(unsigned Opcode,
3436 const MVT *VTs, unsigned NumVTs,
3437 const SDValue *Ops, unsigned NumOps) {
3439 return getNode(Opcode, VTs[0], Ops, NumOps);
3440 return getNode(Opcode, makeVTList(VTs, NumVTs), Ops, NumOps);
3443 SDValue SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3444 const SDValue *Ops, unsigned NumOps) {
3445 if (VTList.NumVTs == 1)
3446 return getNode(Opcode, VTList.VTs[0], Ops, NumOps);
3449 // FIXME: figure out how to safely handle things like
3450 // int foo(int x) { return 1 << (x & 255); }
3451 // int bar() { return foo(256); }
3453 case ISD::SRA_PARTS:
3454 case ISD::SRL_PARTS:
3455 case ISD::SHL_PARTS:
3456 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
3457 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
3458 return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
3459 else if (N3.getOpcode() == ISD::AND)
3460 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
3461 // If the and is only masking out bits that cannot effect the shift,
3462 // eliminate the and.
3463 unsigned NumBits = VT.getSizeInBits()*2;
3464 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
3465 return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
3471 // Memoize the node unless it returns a flag.
3473 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
3474 FoldingSetNodeID ID;
3475 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
3477 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3478 return SDValue(E, 0);
3480 N = getAllocator().Allocate<UnarySDNode>();
3481 new (N) UnarySDNode(Opcode, VTList, Ops[0]);
3482 } else if (NumOps == 2) {
3483 N = getAllocator().Allocate<BinarySDNode>();
3484 new (N) BinarySDNode(Opcode, VTList, Ops[0], Ops[1]);
3485 } else if (NumOps == 3) {
3486 N = getAllocator().Allocate<TernarySDNode>();
3487 new (N) TernarySDNode(Opcode, VTList, Ops[0], Ops[1], Ops[2]);
3489 N = getAllocator().Allocate<SDNode>();
3490 new (N) SDNode(Opcode, VTList, Ops, NumOps);
3492 CSEMap.InsertNode(N, IP);
3495 N = getAllocator().Allocate<UnarySDNode>();
3496 new (N) UnarySDNode(Opcode, VTList, Ops[0]);
3497 } else if (NumOps == 2) {
3498 N = getAllocator().Allocate<BinarySDNode>();
3499 new (N) BinarySDNode(Opcode, VTList, Ops[0], Ops[1]);
3500 } else if (NumOps == 3) {
3501 N = getAllocator().Allocate<TernarySDNode>();
3502 new (N) TernarySDNode(Opcode, VTList, Ops[0], Ops[1], Ops[2]);
3504 N = getAllocator().Allocate<SDNode>();
3505 new (N) SDNode(Opcode, VTList, Ops, NumOps);
3508 AllNodes.push_back(N);
3512 return SDValue(N, 0);
3515 SDValue SelectionDAG::getNode(unsigned Opcode, SDVTList VTList) {
3516 return getNode(Opcode, VTList, 0, 0);
3519 SDValue SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3521 SDValue Ops[] = { N1 };
3522 return getNode(Opcode, VTList, Ops, 1);
3525 SDValue SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3526 SDValue N1, SDValue N2) {
3527 SDValue Ops[] = { N1, N2 };
3528 return getNode(Opcode, VTList, Ops, 2);
3531 SDValue SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3532 SDValue N1, SDValue N2, SDValue N3) {
3533 SDValue Ops[] = { N1, N2, N3 };
3534 return getNode(Opcode, VTList, Ops, 3);
3537 SDValue SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3538 SDValue N1, SDValue N2, SDValue N3,
3540 SDValue Ops[] = { N1, N2, N3, N4 };
3541 return getNode(Opcode, VTList, Ops, 4);
3544 SDValue SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3545 SDValue N1, SDValue N2, SDValue N3,
3546 SDValue N4, SDValue N5) {
3547 SDValue Ops[] = { N1, N2, N3, N4, N5 };
3548 return getNode(Opcode, VTList, Ops, 5);
3551 SDVTList SelectionDAG::getVTList(MVT VT) {
3552 return makeVTList(SDNode::getValueTypeList(VT), 1);
3555 SDVTList SelectionDAG::getVTList(MVT VT1, MVT VT2) {
3556 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
3557 E = VTList.rend(); I != E; ++I)
3558 if (I->NumVTs == 2 && I->VTs[0] == VT1 && I->VTs[1] == VT2)
3561 MVT *Array = Allocator.Allocate<MVT>(2);
3564 SDVTList Result = makeVTList(Array, 2);
3565 VTList.push_back(Result);
3569 SDVTList SelectionDAG::getVTList(MVT VT1, MVT VT2, MVT VT3) {
3570 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
3571 E = VTList.rend(); I != E; ++I)
3572 if (I->NumVTs == 3 && I->VTs[0] == VT1 && I->VTs[1] == VT2 &&
3576 MVT *Array = Allocator.Allocate<MVT>(3);
3580 SDVTList Result = makeVTList(Array, 3);
3581 VTList.push_back(Result);
3585 SDVTList SelectionDAG::getVTList(const MVT *VTs, unsigned NumVTs) {
3587 case 0: assert(0 && "Cannot have nodes without results!");
3588 case 1: return getVTList(VTs[0]);
3589 case 2: return getVTList(VTs[0], VTs[1]);
3590 case 3: return getVTList(VTs[0], VTs[1], VTs[2]);
3594 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
3595 E = VTList.rend(); I != E; ++I) {
3596 if (I->NumVTs != NumVTs || VTs[0] != I->VTs[0] || VTs[1] != I->VTs[1])
3599 bool NoMatch = false;
3600 for (unsigned i = 2; i != NumVTs; ++i)
3601 if (VTs[i] != I->VTs[i]) {
3609 MVT *Array = Allocator.Allocate<MVT>(NumVTs);
3610 std::copy(VTs, VTs+NumVTs, Array);
3611 SDVTList Result = makeVTList(Array, NumVTs);
3612 VTList.push_back(Result);
3617 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
3618 /// specified operands. If the resultant node already exists in the DAG,
3619 /// this does not modify the specified node, instead it returns the node that
3620 /// already exists. If the resultant node does not exist in the DAG, the
3621 /// input node is returned. As a degenerate case, if you specify the same
3622 /// input operands as the node already has, the input node is returned.
3623 SDValue SelectionDAG::UpdateNodeOperands(SDValue InN, SDValue Op) {
3624 SDNode *N = InN.Val;
3625 assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
3627 // Check to see if there is no change.
3628 if (Op == N->getOperand(0)) return InN;
3630 // See if the modified node already exists.
3631 void *InsertPos = 0;
3632 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
3633 return SDValue(Existing, InN.ResNo);
3635 // Nope it doesn't. Remove the node from its current place in the maps.
3637 RemoveNodeFromCSEMaps(N);
3639 // Now we update the operands.
3640 N->OperandList[0].getVal()->removeUser(0, N);
3641 N->OperandList[0] = Op;
3642 N->OperandList[0].setUser(N);
3643 Op.Val->addUser(0, N);
3645 // If this gets put into a CSE map, add it.
3646 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
3650 SDValue SelectionDAG::
3651 UpdateNodeOperands(SDValue InN, SDValue Op1, SDValue Op2) {
3652 SDNode *N = InN.Val;
3653 assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
3655 // Check to see if there is no change.
3656 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
3657 return InN; // No operands changed, just return the input node.
3659 // See if the modified node already exists.
3660 void *InsertPos = 0;
3661 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
3662 return SDValue(Existing, InN.ResNo);
3664 // Nope it doesn't. Remove the node from its current place in the maps.
3666 RemoveNodeFromCSEMaps(N);
3668 // Now we update the operands.
3669 if (N->OperandList[0] != Op1) {
3670 N->OperandList[0].getVal()->removeUser(0, N);
3671 N->OperandList[0] = Op1;
3672 N->OperandList[0].setUser(N);
3673 Op1.Val->addUser(0, N);
3675 if (N->OperandList[1] != Op2) {
3676 N->OperandList[1].getVal()->removeUser(1, N);
3677 N->OperandList[1] = Op2;
3678 N->OperandList[1].setUser(N);
3679 Op2.Val->addUser(1, N);
3682 // If this gets put into a CSE map, add it.
3683 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
3687 SDValue SelectionDAG::
3688 UpdateNodeOperands(SDValue N, SDValue Op1, SDValue Op2, SDValue Op3) {
3689 SDValue Ops[] = { Op1, Op2, Op3 };
3690 return UpdateNodeOperands(N, Ops, 3);
3693 SDValue SelectionDAG::
3694 UpdateNodeOperands(SDValue N, SDValue Op1, SDValue Op2,
3695 SDValue Op3, SDValue Op4) {
3696 SDValue Ops[] = { Op1, Op2, Op3, Op4 };
3697 return UpdateNodeOperands(N, Ops, 4);
3700 SDValue SelectionDAG::
3701 UpdateNodeOperands(SDValue N, SDValue Op1, SDValue Op2,
3702 SDValue Op3, SDValue Op4, SDValue Op5) {
3703 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
3704 return UpdateNodeOperands(N, Ops, 5);
3707 SDValue SelectionDAG::
3708 UpdateNodeOperands(SDValue InN, const SDValue *Ops, unsigned NumOps) {
3709 SDNode *N = InN.Val;
3710 assert(N->getNumOperands() == NumOps &&
3711 "Update with wrong number of operands");
3713 // Check to see if there is no change.
3714 bool AnyChange = false;
3715 for (unsigned i = 0; i != NumOps; ++i) {
3716 if (Ops[i] != N->getOperand(i)) {
3722 // No operands changed, just return the input node.
3723 if (!AnyChange) return InN;
3725 // See if the modified node already exists.
3726 void *InsertPos = 0;
3727 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, NumOps, InsertPos))
3728 return SDValue(Existing, InN.ResNo);
3730 // Nope it doesn't. Remove the node from its current place in the maps.
3732 RemoveNodeFromCSEMaps(N);
3734 // Now we update the operands.
3735 for (unsigned i = 0; i != NumOps; ++i) {
3736 if (N->OperandList[i] != Ops[i]) {
3737 N->OperandList[i].getVal()->removeUser(i, N);
3738 N->OperandList[i] = Ops[i];
3739 N->OperandList[i].setUser(N);
3740 Ops[i].Val->addUser(i, N);
3744 // If this gets put into a CSE map, add it.
3745 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
3749 /// DropOperands - Release the operands and set this node to have
3751 void SDNode::DropOperands() {
3752 // Unlike the code in MorphNodeTo that does this, we don't need to
3753 // watch for dead nodes here.
3754 for (op_iterator I = op_begin(), E = op_end(); I != E; ++I)
3755 I->getVal()->removeUser(std::distance(op_begin(), I), this);
3760 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
3763 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
3765 SDVTList VTs = getVTList(VT);
3766 return SelectNodeTo(N, MachineOpc, VTs, 0, 0);
3769 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
3770 MVT VT, SDValue Op1) {
3771 SDVTList VTs = getVTList(VT);
3772 SDValue Ops[] = { Op1 };
3773 return SelectNodeTo(N, MachineOpc, VTs, Ops, 1);
3776 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
3777 MVT VT, SDValue Op1,
3779 SDVTList VTs = getVTList(VT);
3780 SDValue Ops[] = { Op1, Op2 };
3781 return SelectNodeTo(N, MachineOpc, VTs, Ops, 2);
3784 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
3785 MVT VT, SDValue Op1,
3786 SDValue Op2, SDValue Op3) {
3787 SDVTList VTs = getVTList(VT);
3788 SDValue Ops[] = { Op1, Op2, Op3 };
3789 return SelectNodeTo(N, MachineOpc, VTs, Ops, 3);
3792 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
3793 MVT VT, const SDValue *Ops,
3795 SDVTList VTs = getVTList(VT);
3796 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
3799 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
3800 MVT VT1, MVT VT2, const SDValue *Ops,
3802 SDVTList VTs = getVTList(VT1, VT2);
3803 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
3806 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
3808 SDVTList VTs = getVTList(VT1, VT2);
3809 return SelectNodeTo(N, MachineOpc, VTs, (SDValue *)0, 0);
3812 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
3813 MVT VT1, MVT VT2, MVT VT3,
3814 const SDValue *Ops, unsigned NumOps) {
3815 SDVTList VTs = getVTList(VT1, VT2, VT3);
3816 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
3819 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
3822 SDVTList VTs = getVTList(VT1, VT2);
3823 SDValue Ops[] = { Op1 };
3824 return SelectNodeTo(N, MachineOpc, VTs, Ops, 1);
3827 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
3829 SDValue Op1, SDValue Op2) {
3830 SDVTList VTs = getVTList(VT1, VT2);
3831 SDValue Ops[] = { Op1, Op2 };
3832 return SelectNodeTo(N, MachineOpc, VTs, Ops, 2);
3835 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
3837 SDValue Op1, SDValue Op2,
3839 SDVTList VTs = getVTList(VT1, VT2);
3840 SDValue Ops[] = { Op1, Op2, Op3 };
3841 return SelectNodeTo(N, MachineOpc, VTs, Ops, 3);
3844 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
3845 SDVTList VTs, const SDValue *Ops,
3847 return MorphNodeTo(N, ~MachineOpc, VTs, Ops, NumOps);
3850 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
3852 SDVTList VTs = getVTList(VT);
3853 return MorphNodeTo(N, Opc, VTs, 0, 0);
3856 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
3857 MVT VT, SDValue Op1) {
3858 SDVTList VTs = getVTList(VT);
3859 SDValue Ops[] = { Op1 };
3860 return MorphNodeTo(N, Opc, VTs, Ops, 1);
3863 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
3864 MVT VT, SDValue Op1,
3866 SDVTList VTs = getVTList(VT);
3867 SDValue Ops[] = { Op1, Op2 };
3868 return MorphNodeTo(N, Opc, VTs, Ops, 2);
3871 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
3872 MVT VT, SDValue Op1,
3873 SDValue Op2, SDValue Op3) {
3874 SDVTList VTs = getVTList(VT);
3875 SDValue Ops[] = { Op1, Op2, Op3 };
3876 return MorphNodeTo(N, Opc, VTs, Ops, 3);
3879 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
3880 MVT VT, const SDValue *Ops,
3882 SDVTList VTs = getVTList(VT);
3883 return MorphNodeTo(N, Opc, VTs, Ops, NumOps);
3886 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
3887 MVT VT1, MVT VT2, const SDValue *Ops,
3889 SDVTList VTs = getVTList(VT1, VT2);
3890 return MorphNodeTo(N, Opc, VTs, Ops, NumOps);
3893 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
3895 SDVTList VTs = getVTList(VT1, VT2);
3896 return MorphNodeTo(N, Opc, VTs, (SDValue *)0, 0);
3899 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
3900 MVT VT1, MVT VT2, MVT VT3,
3901 const SDValue *Ops, unsigned NumOps) {
3902 SDVTList VTs = getVTList(VT1, VT2, VT3);
3903 return MorphNodeTo(N, Opc, VTs, Ops, NumOps);
3906 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
3909 SDVTList VTs = getVTList(VT1, VT2);
3910 SDValue Ops[] = { Op1 };
3911 return MorphNodeTo(N, Opc, VTs, Ops, 1);
3914 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
3916 SDValue Op1, SDValue Op2) {
3917 SDVTList VTs = getVTList(VT1, VT2);
3918 SDValue Ops[] = { Op1, Op2 };
3919 return MorphNodeTo(N, Opc, VTs, Ops, 2);
3922 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
3924 SDValue Op1, SDValue Op2,
3926 SDVTList VTs = getVTList(VT1, VT2);
3927 SDValue Ops[] = { Op1, Op2, Op3 };
3928 return MorphNodeTo(N, Opc, VTs, Ops, 3);
3931 /// MorphNodeTo - These *mutate* the specified node to have the specified
3932 /// return type, opcode, and operands.
3934 /// Note that MorphNodeTo returns the resultant node. If there is already a
3935 /// node of the specified opcode and operands, it returns that node instead of
3936 /// the current one.
3938 /// Using MorphNodeTo is faster than creating a new node and swapping it in
3939 /// with ReplaceAllUsesWith both because it often avoids allocating a new
3940 /// node, and because it doesn't require CSE recalulation for any of
3941 /// the node's users.
3943 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
3944 SDVTList VTs, const SDValue *Ops,
3946 // If an identical node already exists, use it.
3948 if (VTs.VTs[VTs.NumVTs-1] != MVT::Flag) {
3949 FoldingSetNodeID ID;
3950 AddNodeIDNode(ID, Opc, VTs, Ops, NumOps);
3951 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3955 RemoveNodeFromCSEMaps(N);
3957 // Start the morphing.
3959 N->ValueList = VTs.VTs;
3960 N->NumValues = VTs.NumVTs;
3962 // Clear the operands list, updating used nodes to remove this from their
3963 // use list. Keep track of any operands that become dead as a result.
3964 SmallPtrSet<SDNode*, 16> DeadNodeSet;
3965 for (SDNode::op_iterator B = N->op_begin(), I = B, E = N->op_end();
3967 SDNode *Used = I->getVal();
3968 Used->removeUser(std::distance(B, I), N);
3969 if (Used->use_empty())
3970 DeadNodeSet.insert(Used);
3973 // If NumOps is larger than the # of operands we currently have, reallocate
3974 // the operand list.
3975 if (NumOps > N->NumOperands) {
3976 if (N->OperandsNeedDelete)
3977 delete[] N->OperandList;
3978 if (N->isMachineOpcode()) {
3979 // We're creating a final node that will live unmorphed for the
3980 // remainder of this SelectionDAG's duration, so we can allocate the
3981 // operands directly out of the pool with no recycling metadata.
3982 N->OperandList = Allocator.Allocate<SDUse>(NumOps);
3983 N->OperandsNeedDelete = false;
3985 N->OperandList = new SDUse[NumOps];
3986 N->OperandsNeedDelete = true;
3990 // Assign the new operands.
3991 N->NumOperands = NumOps;
3992 for (unsigned i = 0, e = NumOps; i != e; ++i) {
3993 N->OperandList[i] = Ops[i];
3994 N->OperandList[i].setUser(N);
3995 SDNode *ToUse = N->OperandList[i].getVal();
3996 ToUse->addUser(i, N);
3997 DeadNodeSet.erase(ToUse);
4000 // Delete any nodes that are still dead after adding the uses for the
4002 SmallVector<SDNode *, 16> DeadNodes;
4003 for (SmallPtrSet<SDNode *, 16>::iterator I = DeadNodeSet.begin(),
4004 E = DeadNodeSet.end(); I != E; ++I)
4005 if ((*I)->use_empty())
4006 DeadNodes.push_back(*I);
4007 RemoveDeadNodes(DeadNodes);
4010 CSEMap.InsertNode(N, IP); // Memoize the new node.
4015 /// getTargetNode - These are used for target selectors to create a new node
4016 /// with specified return type(s), target opcode, and operands.
4018 /// Note that getTargetNode returns the resultant node. If there is already a
4019 /// node of the specified opcode and operands, it returns that node instead of
4020 /// the current one.
4021 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT) {
4022 return getNode(~Opcode, VT).Val;
4024 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT, SDValue Op1) {
4025 return getNode(~Opcode, VT, Op1).Val;
4027 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT,
4028 SDValue Op1, SDValue Op2) {
4029 return getNode(~Opcode, VT, Op1, Op2).Val;
4031 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT,
4032 SDValue Op1, SDValue Op2,
4034 return getNode(~Opcode, VT, Op1, Op2, Op3).Val;
4036 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT,
4037 const SDValue *Ops, unsigned NumOps) {
4038 return getNode(~Opcode, VT, Ops, NumOps).Val;
4040 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2) {
4041 const MVT *VTs = getNodeValueTypes(VT1, VT2);
4043 return getNode(~Opcode, VTs, 2, &Op, 0).Val;
4045 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
4046 MVT VT2, SDValue Op1) {
4047 const MVT *VTs = getNodeValueTypes(VT1, VT2);
4048 return getNode(~Opcode, VTs, 2, &Op1, 1).Val;
4050 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
4051 MVT VT2, SDValue Op1,
4053 const MVT *VTs = getNodeValueTypes(VT1, VT2);
4054 SDValue Ops[] = { Op1, Op2 };
4055 return getNode(~Opcode, VTs, 2, Ops, 2).Val;
4057 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
4058 MVT VT2, SDValue Op1,
4059 SDValue Op2, SDValue Op3) {
4060 const MVT *VTs = getNodeValueTypes(VT1, VT2);
4061 SDValue Ops[] = { Op1, Op2, Op3 };
4062 return getNode(~Opcode, VTs, 2, Ops, 3).Val;
4064 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2,
4065 const SDValue *Ops, unsigned NumOps) {
4066 const MVT *VTs = getNodeValueTypes(VT1, VT2);
4067 return getNode(~Opcode, VTs, 2, Ops, NumOps).Val;
4069 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2, MVT VT3,
4070 SDValue Op1, SDValue Op2) {
4071 const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
4072 SDValue Ops[] = { Op1, Op2 };
4073 return getNode(~Opcode, VTs, 3, Ops, 2).Val;
4075 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2, MVT VT3,
4076 SDValue Op1, SDValue Op2,
4078 const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
4079 SDValue Ops[] = { Op1, Op2, Op3 };
4080 return getNode(~Opcode, VTs, 3, Ops, 3).Val;
4082 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2, MVT VT3,
4083 const SDValue *Ops, unsigned NumOps) {
4084 const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
4085 return getNode(~Opcode, VTs, 3, Ops, NumOps).Val;
4087 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
4088 MVT VT2, MVT VT3, MVT VT4,
4089 const SDValue *Ops, unsigned NumOps) {
4090 std::vector<MVT> VTList;
4091 VTList.push_back(VT1);
4092 VTList.push_back(VT2);
4093 VTList.push_back(VT3);
4094 VTList.push_back(VT4);
4095 const MVT *VTs = getNodeValueTypes(VTList);
4096 return getNode(~Opcode, VTs, 4, Ops, NumOps).Val;
4098 SDNode *SelectionDAG::getTargetNode(unsigned Opcode,
4099 const std::vector<MVT> &ResultTys,
4100 const SDValue *Ops, unsigned NumOps) {
4101 const MVT *VTs = getNodeValueTypes(ResultTys);
4102 return getNode(~Opcode, VTs, ResultTys.size(),
4106 /// getNodeIfExists - Get the specified node if it's already available, or
4107 /// else return NULL.
4108 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
4109 const SDValue *Ops, unsigned NumOps) {
4110 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
4111 FoldingSetNodeID ID;
4112 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
4114 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
4121 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
4122 /// This can cause recursive merging of nodes in the DAG.
4124 /// This version assumes From has a single result value.
4126 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To,
4127 DAGUpdateListener *UpdateListener) {
4128 SDNode *From = FromN.Val;
4129 assert(From->getNumValues() == 1 && FromN.ResNo == 0 &&
4130 "Cannot replace with this method!");
4131 assert(From != To.Val && "Cannot replace uses of with self");
4133 while (!From->use_empty()) {
4134 SDNode::use_iterator UI = From->use_begin();
4137 // This node is about to morph, remove its old self from the CSE maps.
4138 RemoveNodeFromCSEMaps(U);
4140 for (SDNode::op_iterator I = U->op_begin(), E = U->op_end();
4141 I != E; ++I, ++operandNum)
4142 if (I->getVal() == From) {
4143 From->removeUser(operandNum, U);
4146 To.Val->addUser(operandNum, U);
4149 // Now that we have modified U, add it back to the CSE maps. If it already
4150 // exists there, recursively merge the results together.
4151 if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
4152 ReplaceAllUsesWith(U, Existing, UpdateListener);
4153 // U is now dead. Inform the listener if it exists and delete it.
4155 UpdateListener->NodeDeleted(U, Existing);
4156 DeleteNodeNotInCSEMaps(U);
4158 // If the node doesn't already exist, we updated it. Inform a listener if
4161 UpdateListener->NodeUpdated(U);
4166 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
4167 /// This can cause recursive merging of nodes in the DAG.
4169 /// This version assumes From/To have matching types and numbers of result
4172 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To,
4173 DAGUpdateListener *UpdateListener) {
4174 assert(From->getVTList().VTs == To->getVTList().VTs &&
4175 From->getNumValues() == To->getNumValues() &&
4176 "Cannot use this version of ReplaceAllUsesWith!");
4178 // Handle the trivial case.
4182 while (!From->use_empty()) {
4183 SDNode::use_iterator UI = From->use_begin();
4186 // This node is about to morph, remove its old self from the CSE maps.
4187 RemoveNodeFromCSEMaps(U);
4189 for (SDNode::op_iterator I = U->op_begin(), E = U->op_end();
4190 I != E; ++I, ++operandNum)
4191 if (I->getVal() == From) {
4192 From->removeUser(operandNum, U);
4194 To->addUser(operandNum, U);
4197 // Now that we have modified U, add it back to the CSE maps. If it already
4198 // exists there, recursively merge the results together.
4199 if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
4200 ReplaceAllUsesWith(U, Existing, UpdateListener);
4201 // U is now dead. Inform the listener if it exists and delete it.
4203 UpdateListener->NodeDeleted(U, Existing);
4204 DeleteNodeNotInCSEMaps(U);
4206 // If the node doesn't already exist, we updated it. Inform a listener if
4209 UpdateListener->NodeUpdated(U);
4214 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
4215 /// This can cause recursive merging of nodes in the DAG.
4217 /// This version can replace From with any result values. To must match the
4218 /// number and types of values returned by From.
4219 void SelectionDAG::ReplaceAllUsesWith(SDNode *From,
4221 DAGUpdateListener *UpdateListener) {
4222 if (From->getNumValues() == 1) // Handle the simple case efficiently.
4223 return ReplaceAllUsesWith(SDValue(From, 0), To[0], UpdateListener);
4225 while (!From->use_empty()) {
4226 SDNode::use_iterator UI = From->use_begin();
4229 // This node is about to morph, remove its old self from the CSE maps.
4230 RemoveNodeFromCSEMaps(U);
4232 for (SDNode::op_iterator I = U->op_begin(), E = U->op_end();
4233 I != E; ++I, ++operandNum)
4234 if (I->getVal() == From) {
4235 const SDValue &ToOp = To[I->getSDValue().ResNo];
4236 From->removeUser(operandNum, U);
4239 ToOp.Val->addUser(operandNum, U);
4242 // Now that we have modified U, add it back to the CSE maps. If it already
4243 // exists there, recursively merge the results together.
4244 if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
4245 ReplaceAllUsesWith(U, Existing, UpdateListener);
4246 // U is now dead. Inform the listener if it exists and delete it.
4248 UpdateListener->NodeDeleted(U, Existing);
4249 DeleteNodeNotInCSEMaps(U);
4251 // If the node doesn't already exist, we updated it. Inform a listener if
4254 UpdateListener->NodeUpdated(U);
4259 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
4260 /// uses of other values produced by From.Val alone. The Deleted vector is
4261 /// handled the same way as for ReplaceAllUsesWith.
4262 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To,
4263 DAGUpdateListener *UpdateListener){
4264 // Handle the really simple, really trivial case efficiently.
4265 if (From == To) return;
4267 // Handle the simple, trivial, case efficiently.
4268 if (From.Val->getNumValues() == 1) {
4269 ReplaceAllUsesWith(From, To, UpdateListener);
4273 // Get all of the users of From.Val. We want these in a nice,
4274 // deterministically ordered and uniqued set, so we use a SmallSetVector.
4275 SmallSetVector<SDNode*, 16> Users(From.Val->use_begin(), From.Val->use_end());
4277 while (!Users.empty()) {
4278 // We know that this user uses some value of From. If it is the right
4279 // value, update it.
4280 SDNode *User = Users.back();
4283 // Scan for an operand that matches From.
4284 SDNode::op_iterator Op = User->op_begin(), E = User->op_end();
4285 for (; Op != E; ++Op)
4286 if (*Op == From) break;
4288 // If there are no matches, the user must use some other result of From.
4289 if (Op == E) continue;
4291 // Okay, we know this user needs to be updated. Remove its old self
4292 // from the CSE maps.
4293 RemoveNodeFromCSEMaps(User);
4295 // Update all operands that match "From" in case there are multiple uses.
4296 for (; Op != E; ++Op) {
4298 From.Val->removeUser(Op-User->op_begin(), User);
4301 To.Val->addUser(Op-User->op_begin(), User);
4305 // Now that we have modified User, add it back to the CSE maps. If it
4306 // already exists there, recursively merge the results together.
4307 SDNode *Existing = AddNonLeafNodeToCSEMaps(User);
4309 if (UpdateListener) UpdateListener->NodeUpdated(User);
4310 continue; // Continue on to next user.
4313 // If there was already an existing matching node, use ReplaceAllUsesWith
4314 // to replace the dead one with the existing one. This can cause
4315 // recursive merging of other unrelated nodes down the line.
4316 ReplaceAllUsesWith(User, Existing, UpdateListener);
4318 // User is now dead. Notify a listener if present.
4319 if (UpdateListener) UpdateListener->NodeDeleted(User, Existing);
4320 DeleteNodeNotInCSEMaps(User);
4324 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
4325 /// uses of other values produced by From.Val alone. The same value may
4326 /// appear in both the From and To list. The Deleted vector is
4327 /// handled the same way as for ReplaceAllUsesWith.
4328 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
4331 DAGUpdateListener *UpdateListener){
4332 // Handle the simple, trivial case efficiently.
4334 return ReplaceAllUsesOfValueWith(*From, *To, UpdateListener);
4336 SmallVector<std::pair<SDNode *, unsigned>, 16> Users;
4337 for (unsigned i = 0; i != Num; ++i)
4338 for (SDNode::use_iterator UI = From[i].Val->use_begin(),
4339 E = From[i].Val->use_end(); UI != E; ++UI)
4340 Users.push_back(std::make_pair(*UI, i));
4342 while (!Users.empty()) {
4343 // We know that this user uses some value of From. If it is the right
4344 // value, update it.
4345 SDNode *User = Users.back().first;
4346 unsigned i = Users.back().second;
4349 // Scan for an operand that matches From.
4350 SDNode::op_iterator Op = User->op_begin(), E = User->op_end();
4351 for (; Op != E; ++Op)
4352 if (*Op == From[i]) break;
4354 // If there are no matches, the user must use some other result of From.
4355 if (Op == E) continue;
4357 // Okay, we know this user needs to be updated. Remove its old self
4358 // from the CSE maps.
4359 RemoveNodeFromCSEMaps(User);
4361 // Update all operands that match "From" in case there are multiple uses.
4362 for (; Op != E; ++Op) {
4363 if (*Op == From[i]) {
4364 From[i].Val->removeUser(Op-User->op_begin(), User);
4367 To[i].Val->addUser(Op-User->op_begin(), User);
4371 // Now that we have modified User, add it back to the CSE maps. If it
4372 // already exists there, recursively merge the results together.
4373 SDNode *Existing = AddNonLeafNodeToCSEMaps(User);
4375 if (UpdateListener) UpdateListener->NodeUpdated(User);
4376 continue; // Continue on to next user.
4379 // If there was already an existing matching node, use ReplaceAllUsesWith
4380 // to replace the dead one with the existing one. This can cause
4381 // recursive merging of other unrelated nodes down the line.
4382 ReplaceAllUsesWith(User, Existing, UpdateListener);
4384 // User is now dead. Notify a listener if present.
4385 if (UpdateListener) UpdateListener->NodeDeleted(User, Existing);
4386 DeleteNodeNotInCSEMaps(User);
4390 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
4391 /// based on their topological order. It returns the maximum id and a vector
4392 /// of the SDNodes* in assigned order by reference.
4393 unsigned SelectionDAG::AssignTopologicalOrder(std::vector<SDNode*> &TopOrder) {
4394 unsigned DAGSize = AllNodes.size();
4395 std::vector<unsigned> InDegree(DAGSize);
4396 std::vector<SDNode*> Sources;
4398 // Use a two pass approach to avoid using a std::map which is slow.
4400 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ++I){
4403 unsigned Degree = N->use_size();
4404 InDegree[N->getNodeId()] = Degree;
4406 Sources.push_back(N);
4410 TopOrder.reserve(DAGSize);
4411 while (!Sources.empty()) {
4412 SDNode *N = Sources.back();
4414 TopOrder.push_back(N);
4415 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
4416 SDNode *P = I->getVal();
4417 unsigned Degree = --InDegree[P->getNodeId()];
4419 Sources.push_back(P);
4423 // Second pass, assign the actual topological order as node ids.
4425 for (std::vector<SDNode*>::iterator TI = TopOrder.begin(),TE = TopOrder.end();
4427 (*TI)->setNodeId(Id++);
4434 //===----------------------------------------------------------------------===//
4436 //===----------------------------------------------------------------------===//
4438 // Out-of-line virtual method to give class a home.
4439 void SDNode::ANCHOR() {}
4440 void UnarySDNode::ANCHOR() {}
4441 void BinarySDNode::ANCHOR() {}
4442 void TernarySDNode::ANCHOR() {}
4443 void HandleSDNode::ANCHOR() {}
4444 void ConstantSDNode::ANCHOR() {}
4445 void ConstantFPSDNode::ANCHOR() {}
4446 void GlobalAddressSDNode::ANCHOR() {}
4447 void FrameIndexSDNode::ANCHOR() {}
4448 void JumpTableSDNode::ANCHOR() {}
4449 void ConstantPoolSDNode::ANCHOR() {}
4450 void BasicBlockSDNode::ANCHOR() {}
4451 void SrcValueSDNode::ANCHOR() {}
4452 void MemOperandSDNode::ANCHOR() {}
4453 void RegisterSDNode::ANCHOR() {}
4454 void DbgStopPointSDNode::ANCHOR() {}
4455 void LabelSDNode::ANCHOR() {}
4456 void ExternalSymbolSDNode::ANCHOR() {}
4457 void CondCodeSDNode::ANCHOR() {}
4458 void ARG_FLAGSSDNode::ANCHOR() {}
4459 void VTSDNode::ANCHOR() {}
4460 void MemSDNode::ANCHOR() {}
4461 void LoadSDNode::ANCHOR() {}
4462 void StoreSDNode::ANCHOR() {}
4463 void AtomicSDNode::ANCHOR() {}
4465 HandleSDNode::~HandleSDNode() {
4469 GlobalAddressSDNode::GlobalAddressSDNode(bool isTarget, const GlobalValue *GA,
4471 : SDNode(isa<GlobalVariable>(GA) &&
4472 cast<GlobalVariable>(GA)->isThreadLocal() ?
4474 (isTarget ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress) :
4476 (isTarget ? ISD::TargetGlobalAddress : ISD::GlobalAddress),
4477 getSDVTList(VT)), Offset(o) {
4478 TheGlobal = const_cast<GlobalValue*>(GA);
4481 MemSDNode::MemSDNode(unsigned Opc, SDVTList VTs, MVT memvt,
4482 const Value *srcValue, int SVO,
4483 unsigned alignment, bool vol)
4484 : SDNode(Opc, VTs), MemoryVT(memvt), SrcValue(srcValue), SVOffset(SVO),
4485 Flags(vol | ((Log2_32(alignment) + 1) << 1)) {
4487 assert(isPowerOf2_32(alignment) && "Alignment is not a power of 2!");
4488 assert(getAlignment() == alignment && "Alignment representation error!");
4489 assert(isVolatile() == vol && "Volatile representation error!");
4492 /// getMemOperand - Return a MachineMemOperand object describing the memory
4493 /// reference performed by this memory reference.
4494 MachineMemOperand MemSDNode::getMemOperand() const {
4496 if (isa<LoadSDNode>(this))
4497 Flags = MachineMemOperand::MOLoad;
4498 else if (isa<StoreSDNode>(this))
4499 Flags = MachineMemOperand::MOStore;
4501 assert(isa<AtomicSDNode>(this) && "Unknown MemSDNode opcode!");
4502 Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
4505 int Size = (getMemoryVT().getSizeInBits() + 7) >> 3;
4506 if (isVolatile()) Flags |= MachineMemOperand::MOVolatile;
4508 // Check if the memory reference references a frame index
4509 const FrameIndexSDNode *FI =
4510 dyn_cast<const FrameIndexSDNode>(getBasePtr().Val);
4511 if (!getSrcValue() && FI)
4512 return MachineMemOperand(PseudoSourceValue::getFixedStack(FI->getIndex()),
4513 Flags, 0, Size, getAlignment());
4515 return MachineMemOperand(getSrcValue(), Flags, getSrcValueOffset(),
4516 Size, getAlignment());
4519 /// Profile - Gather unique data for the node.
4521 void SDNode::Profile(FoldingSetNodeID &ID) {
4522 AddNodeIDNode(ID, this);
4525 /// getValueTypeList - Return a pointer to the specified value type.
4527 const MVT *SDNode::getValueTypeList(MVT VT) {
4528 if (VT.isExtended()) {
4529 static std::set<MVT, MVT::compareRawBits> EVTs;
4530 return &(*EVTs.insert(VT).first);
4532 static MVT VTs[MVT::LAST_VALUETYPE];
4533 VTs[VT.getSimpleVT()] = VT;
4534 return &VTs[VT.getSimpleVT()];
4538 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
4539 /// indicated value. This method ignores uses of other values defined by this
4541 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
4542 assert(Value < getNumValues() && "Bad value!");
4544 // TODO: Only iterate over uses of a given value of the node
4545 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
4546 if (UI.getUse().getSDValue().ResNo == Value) {
4553 // Found exactly the right number of uses?
4558 /// hasAnyUseOfValue - Return true if there are any use of the indicated
4559 /// value. This method ignores uses of other values defined by this operation.
4560 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
4561 assert(Value < getNumValues() && "Bad value!");
4563 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
4564 if (UI.getUse().getSDValue().ResNo == Value)
4571 /// isOnlyUserOf - Return true if this node is the only use of N.
4573 bool SDNode::isOnlyUserOf(SDNode *N) const {
4575 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
4586 /// isOperand - Return true if this node is an operand of N.
4588 bool SDValue::isOperandOf(SDNode *N) const {
4589 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4590 if (*this == N->getOperand(i))
4595 bool SDNode::isOperandOf(SDNode *N) const {
4596 for (unsigned i = 0, e = N->NumOperands; i != e; ++i)
4597 if (this == N->OperandList[i].getVal())
4602 /// reachesChainWithoutSideEffects - Return true if this operand (which must
4603 /// be a chain) reaches the specified operand without crossing any
4604 /// side-effecting instructions. In practice, this looks through token
4605 /// factors and non-volatile loads. In order to remain efficient, this only
4606 /// looks a couple of nodes in, it does not do an exhaustive search.
4607 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
4608 unsigned Depth) const {
4609 if (*this == Dest) return true;
4611 // Don't search too deeply, we just want to be able to see through
4612 // TokenFactor's etc.
4613 if (Depth == 0) return false;
4615 // If this is a token factor, all inputs to the TF happen in parallel. If any
4616 // of the operands of the TF reach dest, then we can do the xform.
4617 if (getOpcode() == ISD::TokenFactor) {
4618 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
4619 if (getOperand(i).reachesChainWithoutSideEffects(Dest, Depth-1))
4624 // Loads don't have side effects, look through them.
4625 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
4626 if (!Ld->isVolatile())
4627 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
4633 static void findPredecessor(SDNode *N, const SDNode *P, bool &found,
4634 SmallPtrSet<SDNode *, 32> &Visited) {
4635 if (found || !Visited.insert(N))
4638 for (unsigned i = 0, e = N->getNumOperands(); !found && i != e; ++i) {
4639 SDNode *Op = N->getOperand(i).Val;
4644 findPredecessor(Op, P, found, Visited);
4648 /// isPredecessorOf - Return true if this node is a predecessor of N. This node
4649 /// is either an operand of N or it can be reached by recursively traversing
4650 /// up the operands.
4651 /// NOTE: this is an expensive method. Use it carefully.
4652 bool SDNode::isPredecessorOf(SDNode *N) const {
4653 SmallPtrSet<SDNode *, 32> Visited;
4655 findPredecessor(N, this, found, Visited);
4659 uint64_t SDNode::getConstantOperandVal(unsigned Num) const {
4660 assert(Num < NumOperands && "Invalid child # of SDNode!");
4661 return cast<ConstantSDNode>(OperandList[Num])->getValue();
4664 std::string SDNode::getOperationName(const SelectionDAG *G) const {
4665 switch (getOpcode()) {
4667 if (getOpcode() < ISD::BUILTIN_OP_END)
4668 return "<<Unknown DAG Node>>";
4669 if (isMachineOpcode()) {
4671 if (const TargetInstrInfo *TII = G->getTarget().getInstrInfo())
4672 if (getMachineOpcode() < TII->getNumOpcodes())
4673 return TII->get(getMachineOpcode()).getName();
4674 return "<<Unknown Machine Node>>";
4677 TargetLowering &TLI = G->getTargetLoweringInfo();
4678 const char *Name = TLI.getTargetNodeName(getOpcode());
4679 if (Name) return Name;
4680 return "<<Unknown Target Node>>";
4682 return "<<Unknown Node>>";
4685 case ISD::DELETED_NODE:
4686 return "<<Deleted Node!>>";
4688 case ISD::PREFETCH: return "Prefetch";
4689 case ISD::MEMBARRIER: return "MemBarrier";
4690 case ISD::ATOMIC_CMP_SWAP: return "AtomicCmpSwap";
4691 case ISD::ATOMIC_LOAD_ADD: return "AtomicLoadAdd";
4692 case ISD::ATOMIC_LOAD_SUB: return "AtomicLoadSub";
4693 case ISD::ATOMIC_LOAD_AND: return "AtomicLoadAnd";
4694 case ISD::ATOMIC_LOAD_OR: return "AtomicLoadOr";
4695 case ISD::ATOMIC_LOAD_XOR: return "AtomicLoadXor";
4696 case ISD::ATOMIC_LOAD_NAND: return "AtomicLoadNand";
4697 case ISD::ATOMIC_LOAD_MIN: return "AtomicLoadMin";
4698 case ISD::ATOMIC_LOAD_MAX: return "AtomicLoadMax";
4699 case ISD::ATOMIC_LOAD_UMIN: return "AtomicLoadUMin";
4700 case ISD::ATOMIC_LOAD_UMAX: return "AtomicLoadUMax";
4701 case ISD::ATOMIC_SWAP: return "AtomicSWAP";
4702 case ISD::PCMARKER: return "PCMarker";
4703 case ISD::READCYCLECOUNTER: return "ReadCycleCounter";
4704 case ISD::SRCVALUE: return "SrcValue";
4705 case ISD::MEMOPERAND: return "MemOperand";
4706 case ISD::EntryToken: return "EntryToken";
4707 case ISD::TokenFactor: return "TokenFactor";
4708 case ISD::AssertSext: return "AssertSext";
4709 case ISD::AssertZext: return "AssertZext";
4711 case ISD::BasicBlock: return "BasicBlock";
4712 case ISD::ARG_FLAGS: return "ArgFlags";
4713 case ISD::VALUETYPE: return "ValueType";
4714 case ISD::Register: return "Register";
4716 case ISD::Constant: return "Constant";
4717 case ISD::ConstantFP: return "ConstantFP";
4718 case ISD::GlobalAddress: return "GlobalAddress";
4719 case ISD::GlobalTLSAddress: return "GlobalTLSAddress";
4720 case ISD::FrameIndex: return "FrameIndex";
4721 case ISD::JumpTable: return "JumpTable";
4722 case ISD::GLOBAL_OFFSET_TABLE: return "GLOBAL_OFFSET_TABLE";
4723 case ISD::RETURNADDR: return "RETURNADDR";
4724 case ISD::FRAMEADDR: return "FRAMEADDR";
4725 case ISD::FRAME_TO_ARGS_OFFSET: return "FRAME_TO_ARGS_OFFSET";
4726 case ISD::EXCEPTIONADDR: return "EXCEPTIONADDR";
4727 case ISD::EHSELECTION: return "EHSELECTION";
4728 case ISD::EH_RETURN: return "EH_RETURN";
4729 case ISD::ConstantPool: return "ConstantPool";
4730 case ISD::ExternalSymbol: return "ExternalSymbol";
4731 case ISD::INTRINSIC_WO_CHAIN: {
4732 unsigned IID = cast<ConstantSDNode>(getOperand(0))->getValue();
4733 return Intrinsic::getName((Intrinsic::ID)IID);
4735 case ISD::INTRINSIC_VOID:
4736 case ISD::INTRINSIC_W_CHAIN: {
4737 unsigned IID = cast<ConstantSDNode>(getOperand(1))->getValue();
4738 return Intrinsic::getName((Intrinsic::ID)IID);
4741 case ISD::BUILD_VECTOR: return "BUILD_VECTOR";
4742 case ISD::TargetConstant: return "TargetConstant";
4743 case ISD::TargetConstantFP:return "TargetConstantFP";
4744 case ISD::TargetGlobalAddress: return "TargetGlobalAddress";
4745 case ISD::TargetGlobalTLSAddress: return "TargetGlobalTLSAddress";
4746 case ISD::TargetFrameIndex: return "TargetFrameIndex";
4747 case ISD::TargetJumpTable: return "TargetJumpTable";
4748 case ISD::TargetConstantPool: return "TargetConstantPool";
4749 case ISD::TargetExternalSymbol: return "TargetExternalSymbol";
4751 case ISD::CopyToReg: return "CopyToReg";
4752 case ISD::CopyFromReg: return "CopyFromReg";
4753 case ISD::UNDEF: return "undef";
4754 case ISD::MERGE_VALUES: return "merge_values";
4755 case ISD::INLINEASM: return "inlineasm";
4756 case ISD::DBG_LABEL: return "dbg_label";
4757 case ISD::EH_LABEL: return "eh_label";
4758 case ISD::DECLARE: return "declare";
4759 case ISD::HANDLENODE: return "handlenode";
4760 case ISD::FORMAL_ARGUMENTS: return "formal_arguments";
4761 case ISD::CALL: return "call";
4764 case ISD::FABS: return "fabs";
4765 case ISD::FNEG: return "fneg";
4766 case ISD::FSQRT: return "fsqrt";
4767 case ISD::FSIN: return "fsin";
4768 case ISD::FCOS: return "fcos";
4769 case ISD::FPOWI: return "fpowi";
4770 case ISD::FPOW: return "fpow";
4773 case ISD::ADD: return "add";
4774 case ISD::SUB: return "sub";
4775 case ISD::MUL: return "mul";
4776 case ISD::MULHU: return "mulhu";
4777 case ISD::MULHS: return "mulhs";
4778 case ISD::SDIV: return "sdiv";
4779 case ISD::UDIV: return "udiv";
4780 case ISD::SREM: return "srem";
4781 case ISD::UREM: return "urem";
4782 case ISD::SMUL_LOHI: return "smul_lohi";
4783 case ISD::UMUL_LOHI: return "umul_lohi";
4784 case ISD::SDIVREM: return "sdivrem";
4785 case ISD::UDIVREM: return "divrem";
4786 case ISD::AND: return "and";
4787 case ISD::OR: return "or";
4788 case ISD::XOR: return "xor";
4789 case ISD::SHL: return "shl";
4790 case ISD::SRA: return "sra";
4791 case ISD::SRL: return "srl";
4792 case ISD::ROTL: return "rotl";
4793 case ISD::ROTR: return "rotr";
4794 case ISD::FADD: return "fadd";
4795 case ISD::FSUB: return "fsub";
4796 case ISD::FMUL: return "fmul";
4797 case ISD::FDIV: return "fdiv";
4798 case ISD::FREM: return "frem";
4799 case ISD::FCOPYSIGN: return "fcopysign";
4800 case ISD::FGETSIGN: return "fgetsign";
4802 case ISD::SETCC: return "setcc";
4803 case ISD::VSETCC: return "vsetcc";
4804 case ISD::SELECT: return "select";
4805 case ISD::SELECT_CC: return "select_cc";
4806 case ISD::INSERT_VECTOR_ELT: return "insert_vector_elt";
4807 case ISD::EXTRACT_VECTOR_ELT: return "extract_vector_elt";
4808 case ISD::CONCAT_VECTORS: return "concat_vectors";
4809 case ISD::EXTRACT_SUBVECTOR: return "extract_subvector";
4810 case ISD::SCALAR_TO_VECTOR: return "scalar_to_vector";
4811 case ISD::VECTOR_SHUFFLE: return "vector_shuffle";
4812 case ISD::CARRY_FALSE: return "carry_false";
4813 case ISD::ADDC: return "addc";
4814 case ISD::ADDE: return "adde";
4815 case ISD::SUBC: return "subc";
4816 case ISD::SUBE: return "sube";
4817 case ISD::SHL_PARTS: return "shl_parts";
4818 case ISD::SRA_PARTS: return "sra_parts";
4819 case ISD::SRL_PARTS: return "srl_parts";
4821 case ISD::EXTRACT_SUBREG: return "extract_subreg";
4822 case ISD::INSERT_SUBREG: return "insert_subreg";
4824 // Conversion operators.
4825 case ISD::SIGN_EXTEND: return "sign_extend";
4826 case ISD::ZERO_EXTEND: return "zero_extend";
4827 case ISD::ANY_EXTEND: return "any_extend";
4828 case ISD::SIGN_EXTEND_INREG: return "sign_extend_inreg";
4829 case ISD::TRUNCATE: return "truncate";
4830 case ISD::FP_ROUND: return "fp_round";
4831 case ISD::FLT_ROUNDS_: return "flt_rounds";
4832 case ISD::FP_ROUND_INREG: return "fp_round_inreg";
4833 case ISD::FP_EXTEND: return "fp_extend";
4835 case ISD::SINT_TO_FP: return "sint_to_fp";
4836 case ISD::UINT_TO_FP: return "uint_to_fp";
4837 case ISD::FP_TO_SINT: return "fp_to_sint";
4838 case ISD::FP_TO_UINT: return "fp_to_uint";
4839 case ISD::BIT_CONVERT: return "bit_convert";
4841 // Control flow instructions
4842 case ISD::BR: return "br";
4843 case ISD::BRIND: return "brind";
4844 case ISD::BR_JT: return "br_jt";
4845 case ISD::BRCOND: return "brcond";
4846 case ISD::BR_CC: return "br_cc";
4847 case ISD::RET: return "ret";
4848 case ISD::CALLSEQ_START: return "callseq_start";
4849 case ISD::CALLSEQ_END: return "callseq_end";
4852 case ISD::LOAD: return "load";
4853 case ISD::STORE: return "store";
4854 case ISD::VAARG: return "vaarg";
4855 case ISD::VACOPY: return "vacopy";
4856 case ISD::VAEND: return "vaend";
4857 case ISD::VASTART: return "vastart";
4858 case ISD::DYNAMIC_STACKALLOC: return "dynamic_stackalloc";
4859 case ISD::EXTRACT_ELEMENT: return "extract_element";
4860 case ISD::BUILD_PAIR: return "build_pair";
4861 case ISD::STACKSAVE: return "stacksave";
4862 case ISD::STACKRESTORE: return "stackrestore";
4863 case ISD::TRAP: return "trap";
4866 case ISD::BSWAP: return "bswap";
4867 case ISD::CTPOP: return "ctpop";
4868 case ISD::CTTZ: return "cttz";
4869 case ISD::CTLZ: return "ctlz";
4872 case ISD::DBG_STOPPOINT: return "dbg_stoppoint";
4873 case ISD::DEBUG_LOC: return "debug_loc";
4876 case ISD::TRAMPOLINE: return "trampoline";
4879 switch (cast<CondCodeSDNode>(this)->get()) {
4880 default: assert(0 && "Unknown setcc condition!");
4881 case ISD::SETOEQ: return "setoeq";
4882 case ISD::SETOGT: return "setogt";
4883 case ISD::SETOGE: return "setoge";
4884 case ISD::SETOLT: return "setolt";
4885 case ISD::SETOLE: return "setole";
4886 case ISD::SETONE: return "setone";
4888 case ISD::SETO: return "seto";
4889 case ISD::SETUO: return "setuo";
4890 case ISD::SETUEQ: return "setue";
4891 case ISD::SETUGT: return "setugt";
4892 case ISD::SETUGE: return "setuge";
4893 case ISD::SETULT: return "setult";
4894 case ISD::SETULE: return "setule";
4895 case ISD::SETUNE: return "setune";
4897 case ISD::SETEQ: return "seteq";
4898 case ISD::SETGT: return "setgt";
4899 case ISD::SETGE: return "setge";
4900 case ISD::SETLT: return "setlt";
4901 case ISD::SETLE: return "setle";
4902 case ISD::SETNE: return "setne";
4907 const char *SDNode::getIndexedModeName(ISD::MemIndexedMode AM) {
4916 return "<post-inc>";
4918 return "<post-dec>";
4922 std::string ISD::ArgFlagsTy::getArgFlagsString() {
4923 std::string S = "< ";
4937 if (getByValAlign())
4938 S += "byval-align:" + utostr(getByValAlign()) + " ";
4940 S += "orig-align:" + utostr(getOrigAlign()) + " ";
4942 S += "byval-size:" + utostr(getByValSize()) + " ";
4946 void SDNode::dump() const { dump(0); }
4947 void SDNode::dump(const SelectionDAG *G) const {
4948 cerr << (void*)this << ": ";
4950 for (unsigned i = 0, e = getNumValues(); i != e; ++i) {
4952 if (getValueType(i) == MVT::Other)
4955 cerr << getValueType(i).getMVTString();
4957 cerr << " = " << getOperationName(G);
4960 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
4961 if (i) cerr << ", ";
4962 cerr << (void*)getOperand(i).Val;
4963 if (unsigned RN = getOperand(i).ResNo)
4967 if (!isTargetOpcode() && getOpcode() == ISD::VECTOR_SHUFFLE) {
4968 SDNode *Mask = getOperand(2).Val;
4970 for (unsigned i = 0, e = Mask->getNumOperands(); i != e; ++i) {
4972 if (Mask->getOperand(i).getOpcode() == ISD::UNDEF)
4975 cerr << cast<ConstantSDNode>(Mask->getOperand(i))->getValue();
4980 if (const ConstantSDNode *CSDN = dyn_cast<ConstantSDNode>(this)) {
4981 cerr << "<" << CSDN->getAPIntValue().toStringUnsigned() << ">";
4982 } else if (const ConstantFPSDNode *CSDN = dyn_cast<ConstantFPSDNode>(this)) {
4983 if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEsingle)
4984 cerr << "<" << CSDN->getValueAPF().convertToFloat() << ">";
4985 else if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEdouble)
4986 cerr << "<" << CSDN->getValueAPF().convertToDouble() << ">";
4988 cerr << "<APFloat(";
4989 CSDN->getValueAPF().convertToAPInt().dump();
4992 } else if (const GlobalAddressSDNode *GADN =
4993 dyn_cast<GlobalAddressSDNode>(this)) {
4994 int offset = GADN->getOffset();
4996 WriteAsOperand(*cerr.stream(), GADN->getGlobal()) << ">";
4998 cerr << " + " << offset;
5000 cerr << " " << offset;
5001 } else if (const FrameIndexSDNode *FIDN = dyn_cast<FrameIndexSDNode>(this)) {
5002 cerr << "<" << FIDN->getIndex() << ">";
5003 } else if (const JumpTableSDNode *JTDN = dyn_cast<JumpTableSDNode>(this)) {
5004 cerr << "<" << JTDN->getIndex() << ">";
5005 } else if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(this)){
5006 int offset = CP->getOffset();
5007 if (CP->isMachineConstantPoolEntry())
5008 cerr << "<" << *CP->getMachineCPVal() << ">";
5010 cerr << "<" << *CP->getConstVal() << ">";
5012 cerr << " + " << offset;
5014 cerr << " " << offset;
5015 } else if (const BasicBlockSDNode *BBDN = dyn_cast<BasicBlockSDNode>(this)) {
5017 const Value *LBB = (const Value*)BBDN->getBasicBlock()->getBasicBlock();
5019 cerr << LBB->getName() << " ";
5020 cerr << (const void*)BBDN->getBasicBlock() << ">";
5021 } else if (const RegisterSDNode *R = dyn_cast<RegisterSDNode>(this)) {
5022 if (G && R->getReg() &&
5023 TargetRegisterInfo::isPhysicalRegister(R->getReg())) {
5024 cerr << " " << G->getTarget().getRegisterInfo()->getName(R->getReg());
5026 cerr << " #" << R->getReg();
5028 } else if (const ExternalSymbolSDNode *ES =
5029 dyn_cast<ExternalSymbolSDNode>(this)) {
5030 cerr << "'" << ES->getSymbol() << "'";
5031 } else if (const SrcValueSDNode *M = dyn_cast<SrcValueSDNode>(this)) {
5033 cerr << "<" << M->getValue() << ">";
5036 } else if (const MemOperandSDNode *M = dyn_cast<MemOperandSDNode>(this)) {
5037 if (M->MO.getValue())
5038 cerr << "<" << M->MO.getValue() << ":" << M->MO.getOffset() << ">";
5040 cerr << "<null:" << M->MO.getOffset() << ">";
5041 } else if (const ARG_FLAGSSDNode *N = dyn_cast<ARG_FLAGSSDNode>(this)) {
5042 cerr << N->getArgFlags().getArgFlagsString();
5043 } else if (const VTSDNode *N = dyn_cast<VTSDNode>(this)) {
5044 cerr << ":" << N->getVT().getMVTString();
5046 else if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(this)) {
5047 const Value *SrcValue = LD->getSrcValue();
5048 int SrcOffset = LD->getSrcValueOffset();
5054 cerr << ":" << SrcOffset << ">";
5057 switch (LD->getExtensionType()) {
5058 default: doExt = false; break;
5060 cerr << " <anyext ";
5070 cerr << LD->getMemoryVT().getMVTString() << ">";
5072 const char *AM = getIndexedModeName(LD->getAddressingMode());
5075 if (LD->isVolatile())
5076 cerr << " <volatile>";
5077 cerr << " alignment=" << LD->getAlignment();
5078 } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(this)) {
5079 const Value *SrcValue = ST->getSrcValue();
5080 int SrcOffset = ST->getSrcValueOffset();
5086 cerr << ":" << SrcOffset << ">";
5088 if (ST->isTruncatingStore())
5090 << ST->getMemoryVT().getMVTString() << ">";
5092 const char *AM = getIndexedModeName(ST->getAddressingMode());
5095 if (ST->isVolatile())
5096 cerr << " <volatile>";
5097 cerr << " alignment=" << ST->getAlignment();
5098 } else if (const AtomicSDNode* AT = dyn_cast<AtomicSDNode>(this)) {
5099 const Value *SrcValue = AT->getSrcValue();
5100 int SrcOffset = AT->getSrcValueOffset();
5106 cerr << ":" << SrcOffset << ">";
5107 if (AT->isVolatile())
5108 cerr << " <volatile>";
5109 cerr << " alignment=" << AT->getAlignment();
5113 static void DumpNodes(const SDNode *N, unsigned indent, const SelectionDAG *G) {
5114 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
5115 if (N->getOperand(i).Val->hasOneUse())
5116 DumpNodes(N->getOperand(i).Val, indent+2, G);
5118 cerr << "\n" << std::string(indent+2, ' ')
5119 << (void*)N->getOperand(i).Val << ": <multiple use>";
5122 cerr << "\n" << std::string(indent, ' ');
5126 void SelectionDAG::dump() const {
5127 cerr << "SelectionDAG has " << AllNodes.size() << " nodes:";
5129 for (allnodes_const_iterator I = allnodes_begin(), E = allnodes_end();
5131 const SDNode *N = I;
5132 if (!N->hasOneUse() && N != getRoot().Val)
5133 DumpNodes(N, 2, this);
5136 if (getRoot().Val) DumpNodes(getRoot().Val, 2, this);
5141 const Type *ConstantPoolSDNode::getType() const {
5142 if (isMachineConstantPoolEntry())
5143 return Val.MachineCPVal->getType();
5144 return Val.ConstVal->getType();